Last active
October 23, 2015 22:40
-
-
Save xfsnowind/0ad974642ab3bbaa2c76 to your computer and use it in GitHub Desktop.
communication from parent to child and triggered by parenton blog "React -- Communication between components" on 2014/06/24
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
| // For Parent.js | |
| var Parent = React.createClass({ | |
| getInitialState: function () { | |
| return { | |
| changedValue: "" | |
| }; | |
| }, | |
| // the callback function for changing the text in <input type="text"></input> | |
| changeHandler: function (event) { | |
| var value = event.target.value; | |
| // update the value of state, react will | |
| // render it and pass it to Child | |
| this.setState({changedValue: value}); | |
| }, | |
| render: function () { | |
| return ( | |
| <div><input onchange="{this.changeHandler}/" type="text" value="Parent"></input> | |
| // once the value "changedValue" is updated by method setState | |
| // react will render the dom and pass it to Child as its prop named "parentChangedValue" | |
| <child parentchangedvalue="{this.state.changedValue}"></child></div> | |
| ); | |
| } | |
| }); | |
| // For Child.js | |
| var Child = React.createClass({ | |
| getInitialState: function () { | |
| return { parentChangedValue: "" }; | |
| }, | |
| componentWillReceiveProps: function (nextProps) { | |
| var result = nextProps.parentChangedValue; | |
| this.setState({parentChangedValue: result}); | |
| }, | |
| render: function () { | |
| return ( | |
| <div><input type="button" value="{this.state.parentChangedValue}"></input></div> | |
| ); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment