【问题标题】:How to start a countdown by clicking on a touchableOpacity in react native?如何通过点击原生反应中的 touchableOpacity 来开始倒计时?
【发布时间】:2020-11-22 16:40:31
【问题描述】:

当按下TouchableOpacity 时如何启动<CountDown/>

我最近发现了 react-native 的倒计时组件。

倒计时自动开始,但我希望它在单击TouchableOpacity 时开始运行。怎么办?

【问题讨论】:

    标签: function react-native countdowntimer touchableopacity onpress


    【解决方案1】:

    这是一个非常基本的例子,可以帮助你

    constructor(props: Object) {
      super(props);
      this.state ={ timer: 3}
    }
    
    componentDidUpdate(){
      if(this.state.timer === 1){ 
        clearInterval(this.interval);
      }
    }
    
    componentWillUnmount(){
     clearInterval(this.interval);
    }
    
    startTimer(){
      this.interval = setInterval(
        () => this.setState((prevState)=> ({ timer: prevState.timer - 1 })),
        1000
      );
    }
    
    render() {
      return (
        <View style={{ flex: 1, justifyContent: 'center', }}>
          <Text> {this.state.timer} </Text>
          <Button title="Start" onPress={() => this.startTimer() } />
        </View> 
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2021-08-27
      • 2023-01-16
      • 2017-12-01
      相关资源
      最近更新 更多