reactjs - 如何在事件处理程序中使用 React useState 挂钩禁用按钮
问题描述
https://codesandbox.io/s/busy-lamport-lfqwt?file=/src/App.js:0-678
使用状态挂钩
const [loading, _setLoading] = useState(false)
需要根据上面的状态禁用一个按钮
return (
<div className="App">
<button type="button"
onClick={handleSubmit}
disabled={loading}> Send </button>
</div>
);
事件处理程序是
async function handleSubmit(event) {
setLoading(true)
console.log(loadingRef.current)
await setTimeout( () => {} , 3000)
setLoading(false)
console.log(loadingRef.current)
}
在 setTimeout 等待三秒钟时,需要禁用该按钮
React 在稍后运行事件处理程序时将默认加载状态存储在闭包中。所以我使用 useRef 来访问处理程序内部的当前值(与需要实现的目标无关)如何根据加载状态禁用按钮三秒钟。
解决方案
您在这里有几个问题:
setTimeout
不会返回 Promise,因此await
不会延迟执行第二次setLoading
调用。- 您正在传递
onclick
(全部小写)而不是onClick
to<Button>
。
解决这些问题(并清除您所说的不相关的 ref 内容),您将进入这个工作示例(demo):
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [loading, setLoading] = useState(false);
async function handleSubmit(event) {
setLoading(true);
console.log(loading);
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 3000)
);
setLoading(false);
console.log(loading);
}
return (
<div className="App">
<button type="button" onClick={handleSubmit} disabled={loading}>
Send
</button>
</div>
);
}
推荐阅读
- python - Snakemake:在一个规则中的每个输入文件之前插入样本名称
- flutter - 单击删除时从 ListView Builder 中删除容器
- visual-studio - 无法在 Visual Studio Code 中键入百分比字符
- c# - VSTO Powerpoint 识别文本框中的占位符
- google-apps-script - 使用 Webhook 从谷歌脚本发送嵌入到不和谐
- python - 使用 Twitter API 从 Twitter 下载视频而不使用第三方库
- javascript - vue3 isCustomElement 正在将组件检测为 vue 组件
- javascript - 如何使用单个变量来使用对象属性?
- r - 重用 R 子 Rmd 文件 - 错误:重复的块标签
- flutter - 为什么这个 Flutter Web 应用每次运行时都会打开一个 dart 文件?