javascript - 无法从 React Native 中的父组件调用子组件方法

标签 javascript reactjs react-native

我有一个 React Native 组件 <Parent>包含一个组件 <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) .

有什么想法吗?

谢谢!

最佳答案

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

发布您可以使用 this.child.current 访问 child

示例代码:

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

Working demo

如果你的子组件通过 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 ref
this.child.current.getWrappedInstance()

关于javascript - 无法从 React Native 中的父组件调用子组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202209/

相关文章:

javascript - react native : Text and Icon inline

javascript - React javascript 中的过程和方法是什么?

arrays - 如何正确地将数组映射到 <Text> (React native)

javascript - 在 Javascript 中,num = +thenum || 是什么意思?假的意思?

javascript - 只渲染大型 React 项目中的特定组件

node.js - 如何将 facebook 爬虫机器人重定向到另一个网页?

html - React Bootstrap 调整文本输入的宽度

android - React Native:任务:app:installDebug失败

javascript - 使用现有对象作为剪切路径的简单方法?

javascript - 扩展主干模型或 View 时,我如何创建在实例而不是原型(prototype)上创建的属性?