使用react实现倒计时抢券功能,按钮自动倒计时进入页面时,卡片中的按钮开始自动 10s 倒计时 倒计时过程中, 倒计时结束后,按钮文案变为抢购
时间: 2023-05-31 19:02:36 浏览: 157
import React, { useState, useEffect } from 'react';
const Countdown = () => {
const [countdown, setCountdown] = useState(10); // 初始化倒计时为10秒
const [isCounting, setIsCounting] = useState(false); // 是否正在倒计时
const [isSoldOut, setIsSoldOut] = useState(false); // 是否已售罄
useEffect(() => {
if (isCounting) {
const timer = setInterval(() => {
setCountdown(prevCountdown => prevCountdown - 1);
}, 1000);
return () => clearInterval(timer);
}
}, [isCounting]);
const handleButtonClick = () => {
setIsCounting(true);
};
const handleCountdownEnd = () => {
setIsCounting(false);
setIsSoldOut(true);
};
return (
<div>
<div>{countdown}</div>
{!isSoldOut && (
<button onClick={handleButtonClick} disabled={isCounting}>
{isCounting ? `${countdown}s 后抢购` : '抢购'}
</button>
)}
{isSoldOut && <div>已售罄</div>}
</div>
);
};
export default Countdown;
阅读全文