const enhance = (WrapperComponent) => {
return class extends Component {
constructor(props){
super(props)
this.state = {
fields: {}
}
}
getField(fieldName) {
if (!this.state.fields[fieldName]) {
this.state.fields[fieldName] = {
value: '',
onChange: event => {
this.state.fields[fieldName].value = event.target.value
this.forceUpdate()
}
}
}
return {
value: this.state.fields[fieldName].value,
onChange: this.state.fields[fieldName].onChange
}
}
render() {
const props = Object.assign({}, this.props, {
fields: this.getField.bind(this),
})
return (
<WrapperComponent {...props}/>
)
}
}
}
class MyComponent extends Component {
render() {
return <form>
3. 抽象state, 受控组件
<input type="name" {...this.props.fields('name')}/>
</form>
}
}
export default enhance(MyComponent)