【问题标题】:How to disable form submit button until all input fields are filled in ReactJS?在 ReactJS 中填写所有输入字段之前,如何禁用表单提交按钮?
【发布时间】:2022-01-05 00:41:52
【问题描述】:

我想发送一个表单,所以我为此创建了一个函数。我有一个提交表单,在表单的所有字段都填满之前,该按钮不应该启用。

所有验证都在工作,但这不是问题,我需要它来处理 onclick 事件。

我的代码可以工作,但是当我单击复选框使其为真并再次单击使其为假时,该按钮应该禁用,但它会再次启用。 ...

const [name, setName] = useState("");
  const [surname, setSurname] = useState("");
  const [email, setEmail] = useState("");
  const [checkbox, setCheckbox] = useState(false);
  let handleSubmit = async (e) => {
    e.preventDefault();
    try {
      ...
    }
  };
return(
<Input
                      required
                      type="text"
                      value={name}
                      placeholder="İsim"
                      onChange={(e) => setName(e.target.value)}
                    />
<Input
                      required
                      type="text"
                      value={surname}
                      placeholder="Soyisim"
                      onChange={(e) => setSurname(e.target.value)}
                    />
<Input
                      required
                      type="email"
                      placeholder="E-mail"
                      onChange={(e) => setEmail(e.target.value)}
                    />
<Input
                      type="checkbox"
                      required
                      value={checkbox}
                      onChange={(e) => setCheckbox(e.target.value)}
                    />
<input
                  type="submit"
                  name="Onaylıyorum"
                  disabled={!name || !surname || !email || !checkbox}
                />

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    对于复选框,您必须将value 属性更改为checked 属性并访问event.target.checked,而不是即

     <input type="checkbox" checked={checkbox} onChange={(e) => setCheckbox(e.target.checked)} />
    

    react docs也有例子

    【讨论】:

      【解决方案2】:

      复选框很特殊,没有.value,相反,您希望在您的复选框onChange 函数中查找.checked。

      像这样……

      onChange={(e) =&gt; setCheckbox(e.target.checked)}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多