首页 > 解决方案 > 无法从 React Native 中的父组件调用子组件方法

问题描述

我有一个<Parent>包含组件的 React Native 组件<Child>,我希望能够在 Parent 中调用 Child 的方法之一。在阅读了一堆其他帖子之后,这就是我所拥有的:

Child.js

export default class Child extends Component {
  method1() {
    console.log("success");
  }
  render() {
    return(
      <View/>
    )
  }
}

家长

export default class Parent extends Component {
  render() {
    return(
      <View>
        <TouchableOpacity
          onPress={() => this.child.method1()}
        />
        <Child
          onRef={ref => (this.child = ref)}
        />
      </View>
    )
  }
}

我收到错误“_this2.child.method1 不是函数”。

我尝试过的其他事情是使用refInput代替onRef,并做ref => {this.child = ref}代替ref => (this.child = ref)

有任何想法吗?

谢谢!

标签: javascriptreactjsreact-native

解决方案


您可以在构造函数中使用创建一个 ref并使用propReact.createRef将其分配给子组件实例ref

发布您可以使用访问孩子的帖子this.child.current

示例代码:

class Child extends React.Component {
  myMethod() {
    console.log("myMethod called");
  }

  render() {
    return <Text>This is child</Text>;
  }
}

class App extends Component {
  constructor() {
    super();
    this.child = React.createRef();
  }
  render() {
    return (
      <View style={styles.app}>
        <View style={styles.header}>
          <Image
            accessibilityLabel="React logo"
            source={{ uri: logoUri }}
            resizeMode="contain"
            style={styles.logo}
          />
          <Text style={styles.title}>React Native for Web</Text>
        </View>
        <Child ref={this.child} />
        <Button
          onPress={() => {
            this.child.current.myMethod();
          }}
          title="Example button(Click to trigger Child)"
        />
      </View>
    );
  }
}

工作演示

如果您的子组件通过 redux 的 connect 连接,您仍然可以通过在 connect 中将 withRef 选项设置为 true 来访问 childRef

connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(Child);

如果你使用的是 v6 或更高版本的 redux,请设置 forwardRef 属性而不是 withRef

connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(Child);

一旦你在父母中这样做,你将能够访问 cchild 参考

this.child.current.getWrappedInstance()

推荐阅读