Last active
October 26, 2016 15:03
-
-
Save alsma/f837a0f9942fa2822f5f2e4ffb35b486 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, PropTypes } from 'react'; | |
class FormClass extends Component { | |
static propTypes = { | |
onSubmit: PropTypes.func.isRequired, | |
setRef: PropTypes.func, | |
}; | |
constructor(props) { | |
super(props); | |
this.state = this.prepareState(); | |
} | |
componentWillMount() { | |
this.props.setRef && this.props.setRef(this); | |
} | |
componentWillUnmount() { | |
this.props.setRef && this.props.setRef(null); | |
} | |
prepareState() { | |
return { field1: '', field2: '' } | |
} | |
reset() { | |
this.setState(this.prepareState()); | |
} | |
handleChange(id, value) { | |
this.setState({ [id]: value }); | |
} | |
handleSubmit() { | |
this.props.onSubmit(this.state); | |
} | |
render() { | |
return ( | |
<form onSubmit={::this.handleSubmit}> | |
<input id="field1" value={this.state.field1} onChange={(e) => this.handleChange(e.target.id, e.target.value)}/> | |
<input id="field2" value={this.state.field2} onChange={(e) => this.handleChange(e.target.id, e.target.value)}/> | |
</form> | |
); | |
} | |
} | |
const CustomForm = compose(hoc1(), hoc2())(FormClass); | |
class Parent extends Component { | |
handleFormSubmit(data) { | |
$.post(...).then(this.formRef.reset()); | |
} | |
render() { | |
return <Form onSubmit={::this.handleFormSubmit} setRef={ref => this.formRef = ref }/> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment