我在antd
中具有以下格式,其代码几乎逐字地取自the official website。代码沙箱也是here:
以下代码的问题是,在字段中的每个按键上,onChange方法都会触发三(3)次。如果打开浏览器控制台,也可以在codesandbox链接中进行验证。我想了解为什么会这样,该怎么办。
import React from 'react';
import { Form, Input } from 'antd';
import {FieldData} from 'rc-field-form/es/interface.d.ts';
interface CustomizedFormProps {
onChange: (fields: FieldData[]) => void;
fields: FieldData[];
}
const CustomizedForm: React.FC<CustomizedFormProps> = ({ onChange, fields }) => {
return (
<Form
name="global_state"
layout="inline"
fields={fields}
onFieldsChange={(changedFields, allFields) => {
onChange(allFields);
}}
>
<Form.Item
name="username"
label="Username"
rules={[{ required: true, message: 'Username is required!' }]}
>
<Input />
</Form.Item>
</Form>
);
};
export class AntdFormTest extends React.Component<{}, {fields: FieldData[]}> {
constructor(props: {}) {
super(props);
this.state = {fields: [{name: ['username'], value: 'Ant Design'}]};
}
render() {
return (
<>
<CustomizedForm
fields={this.state.fields}
onChange={newFields => {
console.log('onChange fired');
this.setState({fields: newFields});
}}
/>
<pre className="language-bash">{JSON.stringify(this.state, null, 2)}</pre>
</>
);
}
};
答案 0 :(得分:2)
您应该改用onValuesChange
方法。 onFieldsChange
在更新(重新渲染)字段时触发。在此处查看更多信息:https://ant.design/components/form/#API
Here说明了何时应使用OnFieldsChange
方法