使用react-native从父级调用子级方法

时间:2020-06-02 17:43:44

标签: reactjs react-native methods parent-child

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

孩子:

returning to the original name

父母:

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

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

2 个答案:

答案 0 :(得分:4)

您可以在此示例中进行操作。在这里,我使用了React.createRef并将ref传递给child,然后我叫this.child.current.getAlert

import React, {useRef} from "react";

export default class MyParent extends React.Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  onClick = () => {
    this.child.current.getAlert('Mr. Kamal');
  };

  render() {
    return (
      <div>
        <Child ref={this.child} />
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

class Child extends React.Component {
    getAlert(name) {
        alert(`Hi ${name}`);
    }

    render() {
        return <h1>Hello</h1>;
    }
}

答案 1 :(得分:1)

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

onPress={() => this.child.exampleMethod()}

此外,我认为child = CustomComp无效,因为ref={child => {this.child = child}}不受child = CustomComp的影响。

因此,您的Parent js文件应如下所示。

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>
    );
  }
}