React MaterialUI-单击按钮后在TextField组件上设置错误

我有一个输入表单,我想在单击“搜索”按钮后验证输入字段。

Most answers I have seen are having the input validated live, as the user enters it into the form.
I don't want to do this as some of the validation I need to do is a costly operation (validating an API key for example), therefore constantly checking it as it's entered is not an option.
This is also a serverless, single page application, and as far as I could tell - onSubmit would reload the page, so I'm not using that.

我有一个简单的表单,看起来与此类似:

    const [formData, setFormData] = useState({});
    .......
    function handleFormChange(event) {
        let data = formData;
        data[event.target.name] = event.target.value;
        setFormData(data);
    }
    ........
    <form id="search-form" >
       <TextField name="apiKey" label="API Key" onChange={handleFormChange} defaultValue={formData.apiKey} />
       <TextField name='itemName' label="Enter Item" onChange={handleFormChange} />
       <Button name='search-button' onClick={validate} >Search</Button>
    </form>

I can't work out what to put into validate() to either set the errors on the text fields or perform the search. I've tried passing a function into the error prop that checks to see if an errors state variable is populated, I've tried looking into using refs to set the error state but I couldn't see any function that would set the error state.

formData变量将保存当前数据,因此很容易检查“此数据是否有效”,但就我的一生而言,我不知道如何手动触发错误状态。

我正在使用React hooks仅供参考

评论
北城=忆
北城=忆

Implement a validation function and call it when you submit your form. Maintain a state for error and update it when form is invalid. Use material UI error prop to display errors beside your fields.

Working demo is here

代码段

export default () => {
  const [formData, setFormData] = useState({
    apiKey: "test"
  });
  const [isFormInvalid, setIsFormInvalid] = useState(false);

  const validate = values => {
    if (values.apiKey !== "") {
      setIsFormInvalid(false);
    } else {
      setIsFormInvalid(true);
    }
  };
  function handleFormChange(event) {
    let data = formData;
    data[event.target.name] = event.target.value;
    setFormData(data);
  }
  const handleSubmit = e => {
    e.preventDefault();
    if (validate(formData)) {
      // proceed to submit
    }
  };
  return (
    <div className="col-sm-12">
      <h1>My Form</h1>
      <form onSubmit={handleSubmit} id="search-form">
        <TextField
          error={isFormInvalid}
          helperText={isFormInvalid && "api key required"}
          name="apiKey"
          label="API Key"
          onChange={handleFormChange}
          defaultValue={formData.apiKey}
        />

        <Button type="submit" name="search-button" onClick={validate}>
          Search
        </Button>
      </form>
    </div>
  );
};
点赞
评论