import React from 'react'; import Item from './Item'; import { formCreate } from './formCreate'; @formCreate export default class FromDemo extends React.Component { render() { return( <div> <Item fieldName='username' title='username' initialValue='username'> <input /> </Item> <Item fieldName='password' title='password' initialValue='password'> <input /> </Item> <div onClick={() => this.props.handleSubmit(fields => console.log(fields))}>handleSubmit</div> </div> ) } }
使用@formCreate(ES6修飾器語法)後, 直接將React受控組件(onChange & value 形式)如<input />
放在<Item>
裏,無需再給<input />
寫入onChange和value props。
經過this.props.handleSubmit()
獲取form的值。javascript
import React from 'react'; export const formCreate = WrappedComponent => class extends React.Component { state = { fields: {} }; onChange = fieldName => value => this.setFieldValue(fieldName, value); handleSubmit = callback => callback(this.state.fields); getFieldValue = () => this.state.fields; setFieldValue = (fieldName, value) => this.setState(state => { state.fields[fieldName] = value; return state; }); getField = fieldName => ({onChange: this.onChange(fieldName), value: this.state.fields[fieldName]}); setInitialValue = (fieldName, value) => this.setFieldValue(fieldName, value); render() { const props = { ...this.props, handleSubmit: this.handleSubmit, getField: this.getField, getFieldValue: this.getFieldValue, setFieldValue: this.setFieldValue, setInitialValue: this.setInitialValue, }; return <WrappedComponent {...props} ref={ref => this.instanceComponent = ref} />; } };
import React from 'react'; export default class Item extends React.Component { form = this.props.children._owner.stateNode.props; componentDidMount() { this.updateInitialValue(); } componentDidUpdate() { this.updateInitialValue(); } updateInitialValue() { let { fieldName, initialValue } = this.props; (this.initialValue !== initialValue) && (this.initialValue = initialValue) && this.form.setInitialValue(fieldName, initialValue); } render() { let { title, fieldName } = this.props; return( <div> <div>{title}</div> {React.cloneElement(this.props.children, { ...this.form.getField(fieldName) })} </div> ) } }
此處經過抽離state的方式將{onChange, value}以props.getField回調的形式傳遞給受控組件。
initialValue經過Item內部保存一個上一次的initialValue來判斷是否變化。java