我正在使用React JS和Tailwind CSS制作一个倒计时应用程序,目前倒计时运行在useState
钩子的手动输入上,但我想从用户那里获取输入,当用户单击提交按钮时,我想开始倒计时。
请有人能帮助我-我已经被困在这个最后2个小时!谢谢!
代码如下:
App.js -
import React from 'react'
import CountDown from './components/CountDown'
const App = () => {
return (
<div>
<CountDown/>
</div>
)
}
export default App
CountDown.js-
import React, { useState, useEffect, useRef } from 'react'
const CountDown = () => {
const [count, setCount] = useState(10);
let cntVal = useRef();
const handleChange = e =>{
setCount(e.target.value)
}
const handleSubmit = () =>{
if(count < 0){
alert("Count cannot be negative!");
return;
}
}
useEffect(() => {
cntVal.current = setInterval(() => {
setCount(prev => prev - 1)
}, 1000)
return () => clearInterval(cntVal.current)
},[]);
useEffect(() => {
if(count === 0){
clearInterval(cntVal.current);
alert("END!")
}
})
return (
<div className='h-[100vh] w-full flex flex-col items-center justify-center'>
<div className="border border-black p-12 items-center justify-center">
<div className="flex justify-center">
<p className='text-3xl font-bold'>Countdown App</p>
</div>
<div className="flex justify-center mt-10">
<p className='font-semiboldld text-2xl'>{count}</p>
</div>
<div className="flex mt-10 mb-4 items-center justify-center">
<label htmlFor="name" className='text-xl'>Enter a Number: </label>
<input className='border border-black ml-2 p-2 rounded-lg text-xl' type="text" name="cntDown" ref={cntVal} id="cntDown" onChange={handleChange} />
</div>
<div className="flex justify-center">
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={handleSubmit}>
Submit
</button>
</div>
</div>
</div>
)
}
export default CountDown
2条答案
按热度按时间ddrv8njm1#
您可以从
handleSubmit
函数开始倒计时:唯一的其他变化是在您的'卸载'逻辑,检查是否
(cntVal.current)
被设置之前调用clearInterval(cntVal.current)
;wqnecbli2#
看这里