Respond to a function call in a child component

I am trying to call a function that is stored in a child component from a parent. But it is not necessary to do this. I know if there were forms from parent to parent, I could just use the component details, but I'm not sure how to do this from parent to child.

as you can see from the example below, the button in the parent class should trigger the display function in the child class.

var Parent = React.createClass ({ render() { <Button onClick={child.display} ?> } }) var Child = React.createClass ({ getInitialState () { return { display: true }; }, display: function(){ this.setState({ display: !this.state.display }) }, render() { {this.state.display} } }) 
+7
javascript reactjs
source share
2 answers

The easiest way to achieve this is to use refs .

 var Parent = React.createClass ({ triggerChildDisplay: function() { this.refs.child.display(); }, render() { <Button onClick={this.triggerChildDisplay} /> } }) var Child = React.createClass ({ getInitialState () { return { display: true }; }, display: function(){ this.setState({ display: !this.state.display }) }, render() { {this.state.display} } }) 

I basically copied in your example, but notice that in your parent I do not see you display the child component, but usually you would, and on this Child you would give it a link, for example <Child ref="child" /> .

+5
source share

I do not believe that you can call a child function from the parent component.

For this use case, there is a better way to achieve this result, and this means that the "display" property of the child component corresponds to the prop value passed to it by the parent, for example.

 var Parent = React.createClass ({ getInitialState() { return {displayChild: false}; }, toggleChildDisplay() { this.setState({ displayChild: !this.state.displayChild }); }, render() { <Button onClick={this.toggleChildDisplay} /> <Child display={this.state.displayChild} /> } }); var Child = React.createClass ({ render: function() { if (this.props.display) { /*return component*/ } else { /*Don't render*/ } } }); 
0
source share

All Articles