首页 > 解决方案 > 使用 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>;

标签: javascriptreactjs

解决方案


我认为您误解了 useState 钩子。

从 useState 返回的数组如下所示:['currentValue', 'methodToSetValue']

因此,要重置名称,您可以简单地调用setName(""),它将当前值设置为“”。

如果您需要以前的值(例如,不是清除,而是从中更新),您可以将一个函数传递给 setName:

setName(prevName => prevName+' Surname');

这将附加Surname到当前名称。

希望这可以帮助。快乐编码。


推荐阅读