The method for react sub-component to pass value to parent component: set the initial value of state and the function to process the state in the parent component, and pass the function name to the sub-component in the form of props attribute value. The child component calls the function of the parent component, thereby causing state changes, so as to display the changes in the child component in the parent component.
The operating environment of this tutorial: windows7 system, React16 version. This method is suitable for all brands of computers.
Related recommendations: "React Video Tutorial"
The child component needs to control its own state, and then tell the parent component its own state, and call the parent component through props. A function that controls state and displays the state changes of child components in the parent component.
/***实现在输入框输入邮箱时,在p中即时显示输入内容***/ <body> <p id="test"></p> </body> //子组件 var Child = React.createClass({ render: function(){ return ( <p> 邮箱:<input onChange={this.props.handleEmail}/> </p> ) } }); //父组件 var Parent = React.createClass({ getInitialState: function(){ return { email: '' } }, handleEmail: function(event){ this.setState({email: event.target.value}); }, render: function(){ return ( <p> <p>邮箱:{this.state.email}</p> <Child name="email" handleEmail={this.handleEmail.bind(this)}/> </p> ) } }); React.render( <Parent />, document.getElementById('test') );
Principle:
relies on props to pass event references and implements them through callbacks. This implementation is not particularly good, but it works without It's an easy way to implement it without any tool.
Analysis:
In React, the component will only update when the state changes. Set the initial value of state and the function to process the state in the parent component, and pass the function name to the child component in the form of props attribute value. The child component calls the function of the parent component, thereby causing state changes to achieve the goal of changing the state in the parent component. The component displays the changes made by the subcomponent.
For more programming-related knowledge, please visit: Programming Video Course! !
The above is the detailed content of How to pass value from react child component to parent component?. For more information, please follow other related articles on the PHP Chinese website!