【问题标题】:React-Native: Calling a function within a component from parent component inReact-Native:从父组件调用组件内的函数
【发布时间】:2020-11-02 05:45:46
【问题描述】:

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 (evalating '_this.child.testFunc')。

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

有人可以帮帮我吗?

【问题讨论】:

    标签: javascript react-native parent-child


    【解决方案1】:

    在我看来是个糟糕的设计。如果您希望 testFunc() 在父组件中可用,那么您应该在父组件中定义该函数。

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

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

    &lt;ChildComponent func = {testFunc} /&gt;

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-03-11
        • 2016-09-07
        • 2016-12-03
        • 2021-07-15
        • 1970-01-01
        • 2015-11-09
        • 2020-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多