父组件:
import React, { useState, useEffect, useRef } from 'react';
import {Button} from 'antd';
// 控制按钮执行倒计时事件
const [toStart, settoStart] = useState(false);
//组件使用
<Timebutton name={'命中详情'} num={4} onClick={() => {
console.log('3333');
}} toStart={toStart} />
子组件:
import React, { useState, useEffect, useRef } from 'react';
import {Button} from 'antd';
let timeChange: any;
function Timebutton(props: any) {
const { name, num, onClick, toStart } = props;
const [time, setTime] = useState(num);
const [btnDisabled, setBtnDisabled] = useState(false);
const [btnContent, setBtnContent] = useState(name);
useEffect(() => {
if (toStart) {
getClick();
}
}, [toStart]);
useEffect(() => {
clearInterval(timeChange);
return () => clearInterval(timeChange);
}, []);
useEffect(() => {
if (time > 0 && time < num) {
setBtnContent(`${time}${name}`);
} else {
clearInterval(timeChange);
setBtnDisabled(false);
setTime(num);
setBtnContent(name);
}
}, [time]);
const getClick = () => {
setBtnDisabled(true);
timeChange = setInterval(() => setTime((t: number) => --t), 1000);
};
return (
<Button className={styles.rightbtn} type="primary" size="small" ghost disabled={btnDisabled} onClick={() => { onClick() }}>
{btnContent}
</Button>
);
};