javascript - 在 React useEffect 中清除 setInterval 之前,表单不可点击
问题描述
复制行为 沙箱演示的沙箱链接
我在一个 React 组件中有一个钩子,我用它作为回答问题的时间倒计时。
React.useEffect(() => {
const timer = setInterval(() => {
setTimeLeft((newTimeLeft) => newTimeLeft <= 0 ? 0 : newTimeLeft - 1);
}, 50);
return () => {
if(timeLeft <= 0){
clearInterval(timer);
}
};
}, []);
我的表格很简单
<form>
<FormControl>
<RadioGroup aria-label="trivia" name="trivia" value={choice} onChange={handleUserChoice}>
{radioOptions}
</RadioGroup>
<Button variant="outlined" color="secondary" onClick={checkAnswer}>Check Choice</Button>
</FormControl>
</form>
radioOptions
是构成答案选择的无线电组件列表。
radioOptions = currentQuestion.questionInfo.choices.map((option) => {
return (
<FormControlLabel key={option} value={option} control={<Radio />} label={option} />
)
})
直到倒计时结束并调用 clearInterval 后,表单才可交互。我无法单击以选择选项中的任何单选选项。该按钮起作用并触发其功能。但是在间隔完成之前,单选选项不是交互式的。
解决方案
因此,这React.useEffect
只是重新呈现整个选项,因为选项位于同一类中,因此选项被选中,但一旦状态发生变化(即计数器运行),组件就会重新呈现计数器和选择,看起来好像没有被选中。直接从主要组件运行选择有所帮助,并且它像您预期的那样工作
<div className="App">
{timeLeft}
<form>
<p>Select a maintenance drone:</p>
{/* <Choices /> */}
<div>
<input type="radio" id="huey" name="drone" value="huey" />
<label htmlFor="huey">Huey</label>
</div>
<div>
<input type="radio" id="dewey" name="drone" value="dewey" />
<label htmlFor="dewey">Dewey</label>
</div>
<div>
<input type="radio" id="louie" name="drone" value="louie" />
<label htmlFor="louie">Louie</label>
</div>
<button disabled={timeLeft <= 0 ? true : false} onClick={checkChoice}>
Check Choice
</button>
</form>
</div>
推荐阅读
- r - R:合并功能删除实际的行名
- android - 我如何告诉活动完成?
- python - 从解释器运行标头的 Python 脚本
- c# - 指定文件始终是 .csproj 文件之外的 CopyToOutputDirectory
- c - 在 C 中将日期作为字符输入,无法弄清楚如何避免 /
- c# - 使用 linq 查询和选择框的最小值最大值
- javascript - VueJs 条件类/样式绑定?
- c# - 如何将自定义依赖属性添加到 wpf 中的按钮?
- javascript - 如何创建 UI 以允许用户在加载后选择文件的顺序
- jenkins - 如何在当前正在运行的特定 Jenkins 构建中订阅电子邮件通知?