反应如何禁用提交按钮,直到输入表单值



我想保持表单中的提交按钮处于禁用状态,直到每个输入的值至少为一个字符,不包括空格。我尝试使用 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)

使用上面的代码,提交按钮将保持禁用状态,直到我在每个输入中键入至少一个字符(不计算空格,就像我想要的那样),但是一旦我单击提交,我就会收到错误:未捕获的类型错误:无法读取未定义的属性(读取"trim")。

我不明白为什么会这样。在窗体对象上使用 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功能并相应地input state

最新更新