0, requirements,
The Form should have the ability to add and edit Form items. Editing means the Form should have the ability to display data.
Environment:
React: 16.13.1;
Antd 3. X.
Create a form
1. create
Form.create()
React this is a higher-order function that passes in the React component and returns a new React component that changes inside the function.
A component wrapped with form.create () will have its own this.props. Form property.
2. Form data binding
getFieldDecorator(id, options)
Used for bidirectional binding with forms
<! Form data binding --> < form.item {... FormItemLayout} label={' name '}> {getFieldDecorator('searchName')(<Input placeholder={' please Input name '} />)} </ form.item >Copy the code
3. Render the query conditions of the query form
render <Form.Item>
4. Obtain the value of the query condition
form.validateFields / validateFieldsAndScroll
Validates and gets a set of input field values and Error, and if the fieldNames parameter is null, validates all components
const { form } = this.props; Form.validatefields ((err, fieldsValue) => {if (err) return; const { searchName = '' } = fieldsValue; });Copy the code
Implement dynamic forms
1. Effect picture:
- Initial state:
- When I hit +,
- After adding two form items, the delete icon appears.
2. Implement add and remove methods.
Keys is the only value, the id++ used in the official demo, where a random value is overwritten.
function add(props) { const { form } = props; // can use data-binding to get const keys = form.getFieldValue('keys'); const nextKeys = keys && keys.concat(Math.floor(Math.random() * 1000) + 1); // can use data-binding to set // important! notify form to detect changes form.setFieldsValue({ keys: nextKeys, }); } function remove(props, k) { const { form } = props; // can use data-binding to get const keys = form.getFieldValue('keys'); // We need at least one item if (keys && keys.length === 1) { return; } form.setFieldsValue({ keys: keys.filter(key => key ! == k), }); }Copy the code
3. Obtain data from upper-layer components
Using onFieldsChange and mapPropsToFields, you can store the form’s data in an upper-layer component or in Redux or DVA.
- OnFieldsChange: Triggered when the value of the form. Item child changes;
- MapPropsToFields: Maps the parent component’s properties to form items.
Form field data returned in mapPropsToFields must be wrapped in form.CreateFormField.
In the following code, the key name of the return field in mapPropsToFields corresponds to the id name contained in the getFieldDecorator in Render, such as “username “and” keys “in the example.
const CustomForm = Form.create({ name: 'global_state', onFieldsChange(props, changedFields, allFields) { props.onChange(allFields); // changedFields }, mapPropsToFields(props) { return { username: Form.createFormField({ ... props.username, value: props.username.value, }), keys: Form.createFormField({ ... props.keys, value: props.keys && props.keys.value, }), names: props.names && props.names.map(k => ( Form.createFormField({ ... props.names, value: k && k.value, }) )), phones: props.phones && props.phones.map(k => ( Form.createFormField({ ... props.phones, value: k && k.value, }) )), }; }, onValuesChange(props, changedValues, allValues) { console.log(changedValues); }, })(props => { const { getFieldDecorator, getFieldValue } = props.form; getFieldDecorator('keys', { initialValue: [] }); const keys = getFieldValue('keys') || []; const addItems = keys && keys.map((k, Index) = > (< Row gutter = {8} key = {index} > < Col xs = = {12} {24} sm md = = {12} {12} lg xl = {12} > < Form. The Item label = "name" required={false} key={k} > {getFieldDecorator(`names[${index}]`, { validateTrigger: ['onChange', 'onBlur'], rules: [ { whitespace: true, }, ], })(<Input style={{ width: '60%', marginRight: 8 / >)}}} < / Form. The Item > < / Col > < Col xs = = {12} {24} sm md = = {12} {12} lg xl = {12} > < Form. The Item label = "mobile phone Numbers required = {false}" key={k} > {getFieldDecorator(`phones[${index}]`, { validateTrigger: ['onChange', 'onBlur'], rules: [ { whitespace: true, }, ], })(<Input style={{ width: '80%', marginRight: 20 }} />)} {keys.length > 1 ? ( <Icon className="dynamic-delete-button" type="minus-circle-o" onClick={() => remove(props, k)} /> ) : null} </Form.Item> </Col> </Row> )); return ( <Form onSubmit={props.onHandleSubmit} gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }} style={{ marginBottom: 0 }} > <Form.Item label="Username"> {getFieldDecorator('username', { rules: [{ required: true, message: 'Username is required!' }], })(<Input />)} </Form.Item> <Form.Item> <div> <p style={{ display: 'inline-block', margin: '0 10 px'}} > add a message < / p > < Icon type = "plus" onClick = {() = > add (props)} / > < / div > < / Form Item > {addItems} < / Form >). });Copy the code
4. Upper-layer components
export default class MyForm extends React.Component<any, any> { state = { fields: {// Same as the key of the form mapPropsToFields return username: {value: ",}, keys: {value: [],}, names: [], phones: [],},}; handleSubmit = e => { e.preventDefault(); } handleCancel = () => { // this.props.dismissModal(); } handleFormChange = (changedFields) => {this.setState(({fields}) => ({// Update the form field value fields: {... fields, ... changedFields }, })); }; render() { const { fields } = this.state; return ( <> <CustomForm {... fields} onChange={this.handleFormChange} onHandleSubmit={this.handleSubmit} onHandleCancle={this.handleCancel} /> </> ); }}Copy the code
ref
- www.yuque.com/lulu27753/a…
- Juejin. Cn/post / 684490…