React父子组件间方法调用

  • Post author:
  • Post category:其他

1、React 子组件调用父组件方法:(通过props传递)

(1)父组件页面定义changeTypeTable() 方法:

changeTypeTable = value => {
    this.setState({
      typeTable: value,
    });
  };

(2)通过props传递给子组件:

return (
	<Detail
      wrappedComponentRef={form => {
         this.detailForm = form;
      }}
      data={this.state.currentRow}
      changeTypeTable={this.changeTypeTable}
   />

(3)子组件页面通过this.props调用父组件方法:

if (this.props.changeTypeTable !== undefined) {
   this.props.changeTypeTable("666");
}

2、React 父组件调用子组件方法:(通过内容绑定)

(1)父组件页面定义绑定方法onRef():

onRef = ref => {
    this.child = ref;
  };

(2)通过props传递给子组件:

return (
	<Detail
      wrappedComponentRef={form => {
         this.detailForm = form;
      }}
      data={this.state.currentRow}
      onRef={this.onRef}
   />

(3)在子组件页面初始化完成后,通过this.props调用父组件页面onRef()方法把子组件页面内容绑定到父组件。

componentDidMount() {
    if (this.props.onRef !== undefined) {
      this.props.onRef(this);
}
}

并定义相关方法供父组件调用:

changeStepNo = type => {
	console.log(type);
}

(4)父组件中使用this.child调用子组件方法:

this.child.changeStepNo('prev');

版权声明:本文为noeal原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。