簡體   English   中英

React MaterialUI - 單擊按鈕后在 TextField 組件上設置錯誤

[英]React MaterialUI - Set error on TextField Component after button is clicked

我有一個輸入表單,我想在單擊“搜索”按鈕后驗證輸入字段。

我見過的大多數答案都是在用戶將輸入輸入表單時實時驗證輸入。
我不想這樣做,因為我需要做的一些驗證是一項昂貴的操作(例如驗證 API 密鑰),因此在輸入時不斷檢查它不是一種選擇。
這也是一個無服務器的單頁應用程序,據我所知 - onSubmit會重新加載頁面,所以我沒有使用它。

我有一個類似於此的簡單表單:

    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>

我無法弄清楚要在validate()中設置什么以在文本字段上設置錯誤或執行搜索。 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 變量將保存當前數據,因此很容易檢查“此數據是否有效”,但對於我來說,我無法弄清楚如何手動觸發錯誤 state。

我正在使用 React hooks 僅供參考

實現validation function 並在提交表單時調用它。 維護一個 state 的error並在表單無效時更新它。 使用材料 UI錯誤道具在您的字段旁邊顯示錯誤。

工作演示在這里

代碼片段

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>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM