React 类组件实现手机验证码获取及倒计时功能
以下是一个使用 React 类组件实现的获取手机验证码功能,倒计时为 60 秒的示例代码:
import React, { Component } from 'react';
class PhoneVerification extends Component {
constructor(props) {
super(props);
this.state = {
countdown: 60,
isCounting: false,
};
this.timer = null;
}
startCountdown = () => {
if (this.state.isCounting) return;
this.setState({ isCounting: true });
this.timer = setInterval(() => {
if (this.state.countdown === 1) {
clearInterval(this.timer);
this.setState({ countdown: 60, isCounting: false });
} else {
this.setState((prevState) => ({ countdown: prevState.countdown - 1 }));
}
}, 1000);
};
render() {
return (
<div>
<button onClick={this.startCountdown} disabled={this.state.isCounting}>
{this.state.isCounting ? `${this.state.countdown}秒后重新获取` : '获取验证码'}
</button>
</div>
);
}
}
export default PhoneVerification;
在上述代码中,我们使用了一个countdown状态来保存倒计时的剩余秒数,isCounting状态用来表示是否正在进行倒计时。当用户点击获取验证码按钮时,会调用startCountdown方法开始倒计时。在startCountdown方法中,我们使用setInterval每隔一秒更新countdown状态,直到倒计时结束。当倒计时结束时,清除计时器并将countdown重置为 60,同时将isCounting设置为false,以便用户可以再次点击获取验证码按钮。
在组件的render方法中,我们根据isCounting状态来设置按钮的文本和禁用状态。如果正在倒计时,按钮显示剩余秒数,并禁用按钮;否则,按钮显示'获取验证码',并且按钮是可点击的。
你可以将上述代码保存为一个名为PhoneVerification.js的文件,并在其他组件中使用import PhoneVerification from './PhoneVerification'来引入并使用该组件。
使用示例:
import React from 'react';
import PhoneVerification from './PhoneVerification';
function App() {
return (
<div>
<PhoneVerification />
</div>
);
}
export default App;
原文地址: https://www.cveoy.top/t/topic/yKH 著作权归作者所有。请勿转载和采集!