我如何为React原生的倒计时创建功能?

时间:2018-05-01 22:14:45

标签: reactjs react-native

我的本​​地反应技巧是基本的,我想创建一个基本的倒计时,当我点击播放倒计时开始时,就像这个例子:

enter image description here

我的代码:

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>
);
}

2 个答案:

答案 0 :(得分:6)

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> 事件侦听器的按钮。

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

答案 1 :(得分:0)

为防止出现负数,请尝试以下操作:

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