Function 如何通过单击react native中的touchableOpacity开始倒计时?

Function 如何通过单击react native中的touchableOpacity开始倒计时?,function,react-native,countdowntimer,touchableopacity,onpress,Function,React Native,Countdowntimer,Touchableopacity,Onpress,当按下TouchableOpacity时,如何启动 我最近发现了react native的倒计时组件 倒计时会自动开始,但我希望它在我单击TouchableOpacity时开始运行。如何做到这一点?这是一个非常基本的例子,可以帮助您 constructor(props: Object) { super(props); this.state ={ timer: 3} } componentDidUpdate(){ if(this.state.timer === 1){ cl

当按下
TouchableOpacity
时,如何启动

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


倒计时会自动开始,但我希望它在我单击
TouchableOpacity
时开始运行。如何做到这一点?

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

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> 
  )
}
构造函数(道具:对象){
超级(道具);
this.state={timer:3}
}
componentDidUpdate(){
如果(this.state.timer==1){
clearInterval(这个.interval);
}
}
组件将卸载(){
clearInterval(这个.interval);
}
startTimer(){
this.interval=setInterval(
()=>this.setState((prevState)=>({timer:prevState.timer-1})),
1000
);
}
render(){
返回(
{this.state.timer}
this.startTimer()}/>
)
}