从具有本机反应的父级调用子方法

问题描述 投票:0回答:1

我知道这是一个非常普遍的问题,但是我在互联网上发现的一些答案已被弃用。您如何在2020年从父组件中调用子组件的方法?我的实际代码是这样的,但是不起作用

儿童:

export default class CustomComp extends React.Component{
  exampleMethod = () => {
    console.log('pressed');
  };

  render(){
    return (
      ...
    );
  }
}

父母:

export default class App extends React.Component{
  child = CustomComp;
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={this.child.exampleMethod} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}
reactjs react-native methods parent-child
1个回答
0
投票

您必须将函数作为回调调用。

export default class App extends React.Component{
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={() => this.child.exampleMethod()} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.