我正在使用一个名为 Kendo React 的 React 库来创建一个简单的表单。我想要的是能够通过单击“加载新用户”按钮更改数据时提交我的表单,但是当前的行为是,当我单击该按钮并填充数据时,提交按钮不会提交表单,直到我手动更改字段的值,为什么以及如何在更新数据并启用按钮后立即提交表单?这是我的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import { Form, Field, FormElement } from '@progress/kendo-react-form';
import { Error } from '@progress/kendo-react-labels';
import { Input } from '@progress/kendo-react-inputs';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);
const emailValidator = value => emailRegex.test(value) ? "" : "Please enter a valid email.";
const EmailInput = fieldRenderProps => {
const {
validationMessage,
visited,
...others
} = fieldRenderProps;
return <div>
<Input {...others} />
{visited && validationMessage && <Error>{validationMessage}</Error>}
</div>;
};
const App = () => {
const handleSubmit = dataItem => alert(JSON.stringify(dataItem, null, 2));
const [user, setUser] = React.useState({
firstName: 'John',
lastName: 'Smith',
email: 'John.Smith@email.com'
});
const loadNewUser = () => {
setUser({
firstName: 'NewFirstName',
lastName: 'NewLastName',
email: 'NewEmails@email.com'
});
};
return <React.Fragment>
<button className='k-button' onClick={loadNewUser}> Load new user </button>
<hr className='k-hr' />
<Form onSubmit={handleSubmit} initialValues={user} key={JSON.stringify(user)} render={formRenderProps => <FormElement style={{
maxWidth: 650
}}>
<fieldset className={'k-form-fieldset'}>
<legend className={'k-form-legend'}>Please fill in the fields:</legend>
<div className="mb-3">
<Field name={'firstName'} component={Input} label={'First name'} />
</div>
<div className="mb-3">
<Field name={'lastName'} component={Input} label={'Last name'} />
</div>
<div className="mb-3">
<Field name={"email"} type={"email"} component={EmailInput} label={"Email"} validator={emailValidator} />
</div>
</fieldset>
<div className="k-form-buttons">
<button type={'submit'} className="k-button" disabled={!formRenderProps.allowSubmit}>
Submit
</button>
</div>
</FormElement>} />
</React.Fragment>;
};
ReactDOM.render(<App />, document.querySelector('my-app'));