簡體   English   中英

反應如何禁用提交按鈕,直到輸入表單值

[英]React how to disable submit button until form values are input

我想保持表單中的提交按鈕處於禁用狀態,直到每個輸入的值至少是一個字符,不包括空格。 我嘗試使用 trim(),它似乎一直有效,直到我單擊提交。

這是我的表單組件:

export function Form(props) {
  const { form, inputChange, postQuiz } = props;

  const onChange = () => {

    inputChange()
  }

  const onSubmit = evt => {
    evt.preventDefault()
    const question_text_input = document.getElementById("newQuestion");
    const question_text = question_text_input.value
    const true_answer_text_input = document.getElementById("newTrueAnswer");
    const true_answer_text = true_answer_text_input.value
    const false_answer_text_input = document.getElementById("newFalseAnswer");
    const false_answer_text = false_answer_text_input.value
    postQuiz({ question_text, true_answer_text, false_answer_text })
  }

  return (
    <form id="form" onSubmit={onSubmit}>
      <h2>Create New Quiz</h2>
      <input onChange={onChange} placeholder="Enter question" />
      <input onChange={onChange} placeholder="Enter true answer" />
      <input onChange={onChange} placeholder="Enter false answer" />
      <button 
      id="submitNewQuizBtn"
      disabled={
        form.newFalseAnswer.trim().length >= 1
        && form.newTrueAnswer.trim().length >= 1
        && form.newQuestion.trim().length >= 1
        ? ""
        : "disabled"
      }
      >
        Submit new quiz
      </button>
    </form>
  )
}

export default connect(st => st, actionCreators)(Form)

使用上面的代碼,提交按鈕將保持禁用狀態,直到我在每個輸入中至少鍵入一個字符(不包括空格,就像我想要的那樣),但是一旦我單擊提交,我就會收到錯誤消息:Uncaught TypeError: Cannot read properties未定義的(閱讀“修剪”)。

我不明白為什么會這樣。 在表格 Object 上使用 trim() 不正確嗎?

您可以在component中使用two states來實現這一點。 一個用於input ,另一個用於button

const App = () => {
  const [input, setInput] = useState('') // For input
  const [isdisabled, setIsDisabled] = useState(false) // For button

  // when input is changing this function will get called
  const onChange = (e) => {
    setInput((prevState) => (e.target.value))
    if(e.target.value.trim().length < 1) {   // Checking the length of the input
      setIsDisabled(true)  // Disabling the button if length is < 1
    } else {
      setIsDisabled(false)
    }
  }

  const onSubmit = (e) => {
    e.preventDefault()
    // Code...
  }

  return (
    <div className="App">
     <form onSubmit={onSubmit}>
      <input type='text' placeholder='email' value={input} onChange={onChange} />
      <button id='button' type='submit' disabled={isdisabled}>Submit</button>
     </form>
    </div>
  );
}

如果您有多個inputs ,請更改onChange function 並相應地input state

暫無
暫無

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

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