如何基于React Native中的倒数计时器有效地禁用/启用按钮?

我正在创建一个登录屏幕,其中用户必须验证其电话号码,然后单击“重新发送一次性密码(一次性密码)”,然后将一次性密码发送到他的手机。

但是,一旦单击“重新发送OTP”按钮,它应该被禁用30秒钟,并且应该显示倒计时,并且当它达到0时,按钮应该再次被启用。并且该过程应该重新设置,因为他应该能够再次单击它,并且时间应该从30开始重新开始,依此类推。

componentDidUpdate() {
    if (this.state.timer === 1) {
      clearInterval(this.interval);
    }
  }

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

 resendOtp = () => {
    this.setState({
      isButtonDisabled: true,});

    this.interval = setTimeout(() => { return this.setState({
      isButtonDisabled: false,}); },10000);

    this.interval = setInterval(
      () => { return this.setState((prevState) => {
        return { timer: prevState.timer - 1 }; }); },1000
    );

    this.requestOtp();
  }

<Text style={styles.text}>{this.state.timer}</Text>
<TextButton
 title="Resend OTP"
 onPress={this.resendOtp}
 disabled={this.state.isButtonDisabled}
/>
kimle 回答:如何基于React Native中的倒数计时器有效地禁用/启用按钮?

resendOtp = () => {
this.setState({
  isButtonDisabled: true,});

this.setTimeout( () => {
   isButtonDisabled = false
},30000) //this will enable button after 30 seconds you can change time here.

this.interval = setInterval(
  () => { return this.setState((prevState) => {
    return { timer: prevState.timer - 1 }; }); },1000
);

this.requestOtp();

希望这对您有用。

,

onSendAndPlayTimer函数中,您发送所需的信息并播放计时器

<TouchableOpacity
   disabled={this.state.timer != 0}
   onPress={this.onSendAndPlayTimer}>
      <Text>{'Send!'}</Text>
</TouchableOpacity>
本文链接:https://www.f2er.com/3153581.html

大家都在问