javascript - 使用 useState 清除字段
问题描述
我有一个表单,提交时需要清除输入字段。
我正在使用 useState 并且在我的addNewColor
方法中,我正在重置newName
状态以返回到空字符串。初始状态是一个空字符串,所以我想我会打电话setName(newName)
,因为那是我的初始状态,但它不起作用。我知道有一些使用方法prevState
,但我还没有完全理解它。对于令人困惑的总结,我深表歉意。
简而言之,我只是想清理这个领域。我正在使用 Material UI,名称位于 TextValidator 组件中。
const NewPaletteForm = () => {
const [currentColor, setColor] = useState("teal");
const [colors, setColors] = useState([]);
const [newName, setName] = useState("");
function addNewColor() {
const newColor = {
color: currentColor,
name: newName
};
const resetName = {
name: ""
};
setName(newName, resetName);
setColors([...colors, newColor]);
}
function handleChange(event) {
setName(event.target.value);
}
};
<ValidatorForm onSubmit={addNewColor}>
<TextValidator
value={newName}
onChange={handleChange}
validators={["required", "isColorNameUnique", "isColorUnique"]}
errorMessages={[
"Enter a color name",
"Color name must be unique",
"Color is already used"
]}
/>
<Button
variant="contained"
type="submit"
color="primary"
style={{ backgroundColor: currentColor }}
>
Add Color
</Button>
</ValidatorForm>;
解决方案
我认为您误解了 useState 钩子。
从 useState 返回的数组如下所示:['currentValue', 'methodToSetValue']
因此,要重置名称,您可以简单地调用setName("")
,它将当前值设置为“”。
如果您需要以前的值(例如,不是清除,而是从中更新),您可以将一个函数传递给 setName:
setName(prevName => prevName+' Surname');
这将附加Surname
到当前名称。
希望这可以帮助。快乐编码。
推荐阅读
- discord.py - 防止 jar 文件在 repl.it 上终止
- firebase-authentication - 从 Electron Firebase 应用程序在浏览器中打开登录弹出窗口
- boost - 使用 std::move 作为参数传递的共享 ptr 提升 asio 帖子
- python - Python Selenium - 单击没有下一步按钮的页面
- angular - Angular 11 - 延迟加载路由问题
- javascript - 如何在其他异步函数中调用aysnc函数getAffiliatesCodes()
- python - 如何在python中设置默认工作目录?
- java - 如何在 JAX-WS(Spring Boot + Apache CXF)中返回 400 响应而不是 SOAPFault
- ios - 完整性无法验证
- libreoffice - Libre Office 配置文件 bootstrap.ini 损坏