有什么方法可以显示 <Text>使用计时器 setTimeout() 多次? [英] Is there any way to display <Text> with a timer setTimeout() multiple times?
本文介绍了有什么方法可以显示 <Text>使用计时器 setTimeout() 多次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图返回 9 个不同的文本,每个文本之间有 5 秒的延迟,但它仅适用于第一个文本
I'm trying to return 9 differents Text with a 5 seconds delay between each ones but it's only working for the first Text
我试过使用
render() {
setTimeout(() => {this.setState({timePassed: true})}, 2000);
if(this.state.timePassed == false){
return (
<Text></Text>
)
}else if (this.state.timePassed == true{
return(
<Text>HELLO</Text>
)
}else if (this.state.timePassed1 == false{
............
}
}
但不工作我也试过
componentDidUpdate(){
setTimeout(() => {this.setState({timePassed1: true})}, 4000);
if(this.state.timePassed1 == true){
return(
<Text>test</Text>)
}
}
但不工作
这是我的屏幕
export default class Internet2 extends React.Component {
constructor(props){
super(props);
this.state = {
timePassed: false,
timePassed1: false
};
}
componentDidUpdate(){
setTimeout(() => {this.setState({timePassed1: true})}, 4000);
if(this.state.timePassed1 == true){
return(
<Text>test</Text>)
}
}
render() {
setTimeout(() => {this.setState({timePassed: true})}, 2000);
if(this.state.timePassed == false){
return (
<Text></Text>
)
}else{
return(
<Text>HELLO</Text>
)
}
}
}
感谢您的帮助!
推荐答案
你可以做的是将文本保存在一个数组和一个变量中,用于计算它通过了多少次.
What you can do is keep the texts in an array and a variable for counting how many times has it passed.
state = {
texts = ['sometext', ...]
textCount = 0
}
然后您将创建一个 setInterval
以在您想要的时间循环
Then you will create a setInterval
to loop in the time you want
componentDidMount() {
let timer = setInterval(() => {
this.setState(prevState => {
return {textCount: prevState.textCount + 1}
})
if (this.state.textCount > this.state.texts.length) clearInterval(timer);
}, theTimeYouWant);
}
并使用 .map
render() {
return (
<View>
{this.state.texts.map((text, i) => i <= this.state.textCount ?
<Text>{text}</Text> : null
)}
</View>
)
}
这篇关于有什么方法可以显示 <Text>使用计时器 setTimeout() 多次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文