在react项目中,父组件如何调用子组件中方法

例如:父组件中有个按钮,点击按钮弹出弹框,弹框是在子组件里,弹框弹出时需要请求接口展示列表数据,每次点击父组件的按钮时都需要请求数据。所以就需要在父组件中调用子组件的方法。

方法一:

首先父组件的代码:

 

 

 

 

 

 子组件中的代码:

 

 

 简要总结:

子组件:

componentDidMount() {
    this.props.onRef(this);
  }
 
closeTree = () => {
    this.setState({
      isShows: false
    });
  };

  

父组件:

jsx文件里:

onRefTree = ref => {
    // this.childTree = ref;
    this.props.dispatch({
      type: 'updateState',
      payload: {
        childTree: ref
      }
    });
  };
 
 
<Tree onRef={this.onRefTree}>

model文件里:调用子组件里closeTree方法

childTree.closeTree();

posted @ 2021-07-27 11:24  可爱的小猫咪  阅读(2585)  评论(0)    收藏  举报