Call child method from parent

前端 未结 16 2094
长发绾君心
长发绾君心 2020-11-21 22:23

I have two components.

  1. Parent component
  2. Child component

I was trying to call child\'s method from Parent, I tried this way but couldn\

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 23:20

    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.

提交回复
热议问题