我在 React Native 方面的技能是基本的,我想创建一个基本的倒计时,当我点击播放倒计时开始时,就像这个例子:

reactjs - 我如何在 React Native 中创建倒计时功能?-LMLPHP

我的代码:

render() {
return (

<Grid>
<Row>

<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/done.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Done</Text>
</Col>

<Col style={styles.col_exercise}>
<View style={{borderWidth: 2, borderColor: '#f39c12', borderRadius: 50, height: 100, width: 100,alignItems: 'center',
justifyContent: 'center'}}>
<Text style={{fontSize: 18, color: '#000'}}>
00:30
</Text>
</View>
</Col>

<Col style={styles.col_exercise}>
<Image source={require('../../assets/images/play.png')} resizeMode="contain" style={styles.icon_videoexercise} />
<Text style={styles.titlecol_exercise}>Play</Text>
</Col>

</Row>

</Grid>
);
}

最佳答案

constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

componentDidMount() {
 this.clockCall = setInterval(() => {
   this.decrementClock();
 }, 1000);
}

componentWillUnmount() {
 clearInterval(this.clockCall);
}

decrementClock = () => {
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

您可以使用 setInterval 创建倒计时。组件安装后,每隔一秒就会调用一次 this.decrementClock()
您需要在渲染方法中渲染 this.state.timer
constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

startTimer = () => {
 this.clockCall = setInterval(() => {
  this.decrementClock();
 }, 1000);
}

decrementClock = () => {
 if(this.state.timer === 0) clearInterval(this.clockCall)
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

componentWillUnmount() {
 clearInterval(this.clockCall);
}

在渲染中添加带有 Onpress 事件监听器的按钮。
<button Onpress={this.startTimer}> Play </button>

<Text style={{fontSize: 18, color: '#000'}}>
 {this.state.timer === 0 ? 'Times Up!' : {this.state.timer} }
</Text>

关于reactjs - 我如何在 React Native 中创建倒计时功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50124598/

10-12 15:13