gpt4 book ai didi

javascript - 使用 Reactjs 按标签显示 html 标签并延迟

转载 作者:行者123 更新时间:2023-12-01 03:07:48 25 4
gpt4 key购买 nike

我有一个问题,我花了很多时间阅读并尝试解决,但没有成功。

我必须模拟这样的聊天:

Chat first interaction

但是我找不到一种方法来在每个气泡之间进行延迟,它们总是同时显示,我尝试使用我在网上找到的很多函数,例如 setTimeout、await sleep with Promise 等。它们都不起作用,气泡总是同时显示,很多时候延迟本身甚至不起作用,它们在延迟时间结束之前显示。

有人知道如何做吗?我只需要知道如何按照我自己的逻辑来做到这一点。所以基本上我需要知道如何对Reactjs说:“显示一个空页面,2秒后,显示第一个气泡,2秒后,显示第二个气泡”。

代码示例:使用状态:

renderChat(){
let bubbles = this.state.bubbles;
if(this.state.renderSecondBubbles){
bubbles.push(this.renderBubbleResponse(this.state.name));
bubbles.push(<BubbleUs><p>Hello {this.state.name}</p></BubbleUs>)
}else{
if(this.state.renderFirstBubbles){
bubbles.push(<BubbleUs><p>Hello</BubbleUs>)
bubbles.push(<BubbleUs><p>What is your name?</p></BubbleUs>)
}
}
}

render(){
return(
<div>
{this.renderChat()}
</div>
)
}

不使用状态的示例:

render(){
return(
<div>
<BubbleUs>Your account was created</BubbleUs>
<BubbleUs>Now, its time to choose your payment method</BubbleUs>
</div>
)
}

非常感谢大家。

最佳答案

我们当然需要您提供一些代码。您是根据某种状态树渲染这些气泡,还是直接在组件 render() 方法中创建它们?

如果是第二个,我相信您可以使用 lifecycle methods 模拟超时响应在组件中:

import React from 'react';

export class SampleMessages extends React.Component {
contructor(props) {
super(props);

this.state = {
interval: null,
messages: []
};
}

componentDidMount() {
const interval = setInterval(() => {
const newMessages = this.state.messages.concat([ 'New message' ]);

this.setState({ messages: newMessages });
}, 1000);

this.setState({ interval });
}

componentWillUnmount() {
clearInterval(this.state.interval);
}

render() {
const { messages } = this.state;

return (
<div>
{messages.map((text, index) =>
<p key={Math.random() + index}>
{text}
</p>
}
</div>
);
}
}

关于javascript - 使用 Reactjs 按标签显示 html 标签并延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46057712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com