I have two components.
I was trying to call child\'s method from Parent, I tried this way but couldn\
You can use another pattern here:
class Parent extends Component {
render() {
return (
this.clickChild = click}/>
);
}
}
class Child extends Component {
constructor(props) {
super(props);
this.getAlert = this.getAlert.bind(this);
}
componentDidMount() {
this.props.setClick(this.getAlert);
}
getAlert() {
alert('clicked');
}
render() {
return (
Hello
);
}
}
What it does is to set the parent's clickChild
method when child is mounted. In this way when you click the button in parent it will call clickChild
which calls child's getAlert
.
This also works if your child is wrapped with connect()
so you don't need the getWrappedInstance()
hack.
Note you can't use onClick={this.clickChild}
in parent because when parent is rendered child is not mounted so this.clickChild
is not assigned yet. Using onClick={() => this.clickChild()}
is fine because when you click the button this.clickChild
should already be assigned.