我正在尝试根据单击时的验证错误禁用按钮。如果表单输入字段有任何更改,则应启用该按钮,直到这里对我有用。但是当我单击“下一步”时,如果再次出现错误,该按钮应该被禁用,但似乎无法实现。因此,第一次单击按钮可以正常工作,但第二次单击就不行了,因为 authFailed 有错误。有人可以帮我解决这个问题吗?
**Below are the conditions I am using :**
let disableButton=false;
let existingError=false;
const authFailed=hasError(AUTH_FAILED);
if (authFailed && !existingError) {
disableButton=true;
} else {
disableButton=false;
}
if (authFailed) {
existingError=true;
}
**Input Field:**
<Input fieldName="Name" value={value} onChange={()=>{disableButton=false;}} />
**Button:**
<button onClick={() => {
existingError = false;
onButton();
}}`enter code here`
disabled={disableButton}
isLoading={false}
/>
在Input OnChage方法中,不要直接设置disableButton值。 调用函数并相应地设置状态。
const App = () => {
const [state, setState] = React.useState({inputText: "", isValidationError: true});
const onChangeInput = (e) => {
//get text entered
const newtext = e.target.value;
//perform validation (auth etc.) with new text
const validateResult = newtext.length < 4;
//set result to state (do not forget to set also the new text)
setState({
isValidationError: validateResult,
inputText: newtext
})
}
return <div>
<input value={state.inputText} onChange={(e)=>onChangeInput(e)}/>
<button disabled={state.isValidationError}>sample button</button>
</div>
};
const domNode = document.getElementById('root');
const root = ReactDOM.createRoot(domNode);
root.render(<App />);
<div id="root" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>