React-Native:从父组件调用组件内的函数

React-Native: Calling a function within a component from parent component in

Child.js:

export default class Child extends Component {

  testFunc = () => {
   console.log("test")
  }

  componentDidMount() {
    this.props.onRef(this)
 }

Parent.js:

export default class Parent extends Component {

 render() { 
   return (
   <>
     <Child onRef = {ref => (this.child=ref)}> </Child>
     <Button onPress={this.child.testFunc()}></Button>
   </>
   )
 }
}

我想知道如何在 React Native 中从父组件调用子组件中的函数?我尝试了上面的代码,但出现错误“TypeError undefined is not an object (evaluating '_this.child.testFunc').

我在此处尝试建议的解决方案时遇到同样的错误:Call child function from parent component in React Native

有人可以帮我吗?

我觉得设计很糟糕。如果您希望 testFunc() 在父组件中可用,那么您应该在父组件中定义该函数。

为了在子组件中使用此功能,您可以将此功能传递给 props 中的子组件。

从 ParentComponent.js 你可以像这样传递这个函数

<ChildComponent func = {testFunc} />

在ChildComponent.js中你可以像这样回调这个函数 this.props.func()

请试试这个。由于 javascript 语法,在调用 testFunc 时删除括号。

export default class Parent extends Component {

  render() { 
   return (
   <>
     <Child onRef = {ref => (this.child=ref)}> </Child>
     <Button onPress={this.child.testFunc}></Button>
   </>
   )
  }
 }