React
-实现60s
倒计时
当我们点击“获取验证码”后,文字变成
60s
倒计时(隔1s
,秒数-1
),当秒数为0s
时,文字又变回“获取验证码”。❀
class HomePage extends React.Component {
constructor(props) {
super(props);
}
initValue = 60 // 定义倒计时秒数
state = {
// 定义state初始化数据
timer: this.initValue, // 倒计时数
}
// 点击“获取验证码”
getCode = () => {
this.setState({
isClick: true, // true->显示 倒计时秒数;false->显示 “开始倒计时”
})
let auth_timer = setInterval(() => {
// 定时器设置每秒递减
const new_timer = this.state.timer-1; // 递减时间
this.setState({
timer: new_timer,
})
if (this.state.timer <= 0) {
this.setState({
isClick: false, // true->显示 倒计时秒数;false->显示 “开始倒计时”
})
clearInterval(auth_timer); // 清除定时器
this.setState({
timer: this.initValue, // 将秒数恢复到初始数据
})
}
}, 1000)
}
render() {
return (
<div>
{
this?.state?.isClick?
<span>{
this.state.timer}s</span>:
<span onClick={
this.getCode}>获取验证码</span>
}
</div>
);
}
}