To do this, you pass the callback as a property with a child of the parent.
For example:
var Parent = React.createClass({ getInitialState: function() { return { value: 'foo' } }, changeHandler: function(value) { this.setState({ value: value }); }, render: function() { return ( <div> <Child value={this.state.value} onChange={this.changeHandler} /> <span>{this.state.value}</span> </div> ); } }); var Child = React.createClass({ propTypes: { value: React.PropTypes.string, onChange: React.PropTypes.func }, getDefaultProps: function() { return { value: '' }; }, changeHandler: function(e) { if (typeof this.props.onChange === 'function') { this.props.onChange(e.target.value); } }, render: function() { return ( <input type="text" value={this.props.value} onChange={this.changeHandler} /> ); } });
In the above example, Parent calls Child with the value and onChange . The returned Child binds the onChange handler to the standard <input /> element and passes the value until the Parent callback, if one is defined.
As a result, the Parent changeHandler method is changeHandler with the first argument being the string value from the <input /> field in Child . As a result, the Parent state can be updated with this value, as a result of which the parent <span /> element will be updated with the new value when you enter it in the Child input field.
Mike Driver 03 Oct '14 at 13:40 2014-10-03 13:40
source share