ReactNative进阶(二十六):子组件调用父组件中的函数

191 阅读1分钟

需求

在子组件执行某个操作的时候,需要其去调用父组件中的某个函数或者改变父组件中的某个参数。实现方式如下:

子组件

export default class Child extends PureComponent {
  static propTypes = {
    onItemClick: React.PropTypes.func,
  }
  info = '子组件的内容';
  itemClick(index) {
     // 可以将子组件中的某个内容传出给父组件
     if (this.props.onItemClick) {
       this.props.onItemClick(index);
     }
  }
  render(){
      return(
      <TouchableOpacity
            onPress={() => { this.itemClick(this.index); }}
            style={styles.touchItem}
          >
            <Text >
              点击修改父组件内容
            </Text>
          </TouchableOpacity>
      );
  }
}

父组件

export default class Father extends PureComponent {
  _onItemClick(info) {
  	console.log('你调用了父组件的方法')
       // 显示index或者用子组件的参数改变父组件中的参数
    console.log(info);
  }
 render(){
      return(
         <Child
             onItemClick={this._onItemClick}
      );
}
/>