[英]Submit button not changing from disabled to enabled after Validation of field length
I have a React form with just a text area and a submit button.我有一个只有一个文本区域和一个提交按钮的 React 表单。 I set the submit button's state to disabled to begin with, and then after the user enters 100 chars or more I want to enable the Submit button.
我将提交按钮的 state 设置为禁用开始,然后在用户输入 100 个字符或更多字符后,我想启用提交按钮。
The issue I'm having right now is that after I input more than 100 chars, the submit button remains disabled and doesn't change to enabled state.我现在遇到的问题是,在我输入超过 100 个字符后,提交按钮保持禁用状态并且不会更改为启用 state。
This is the updateFieldLength
function I am calling upon the textarea field's onChange
.这是
updateFieldLength
function 我正在调用 textarea 字段的onChange
。
const updateFieldLength = e => (
setText(e.target.value), () => (
validateFieldLength()
)
)
and this is the validateFieldLength
function:这是
validateFieldLength
function:
function validateFieldLength() {
if (submitDisabled && text.length > 100) {
setSubmitDisabled(false);
} else if (!submitDisabled && text.length <= 100) {
setSubmitDisabled(true);
}
}
Your problem seems to be that the onchange event is triggered only when textarea loses focus.您的问题似乎是仅当 textarea 失去焦点时才会触发 onchange 事件。 I guess it would work with the oninput event, shown below
我想它可以与 oninput 事件一起使用,如下所示
const setBackground = (element, background) => { element.style.background = background; }
<textarea id="test-on-change" onchange="setBackground(this, 'green')" rows="10" cols="30">Example with onchange, start typing...</textarea> <textarea id="test-on-input" oninput="setBackground(this, 'yellow')" rows="10" cols="30">Example with oninput, start typing...</textarea>
This should do the job这应该做的工作
import React from 'react'
const MyComponent = () => {
const [text, setText] = useState('')
const handleTextChange = e => {
setText(e.target.value)
}
return(
<>
<textarea onChange={handleTextChange}>
{text}
</textarea>
<button disabled={text.length < 100}>
Submit
</button>
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.