简体   繁体   中英

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

I was wondering how do I call a function that is in a child component from parent component in React Native? I tried the code above and I get the error "TypeError undefined is not an object (evaluating '_this.child.testFunc').

I get the same error when I tried the suggested solution here: Call child function from parent component in React Native .

Could someone help me please?

Looks like a bad design to me. If you want the testFunc() to be available in the parent component then you should define that function in the parent component.

In order to use this function in child component you can pass this function to child in the props.

From ParentComponent.js you can pass this function like this

<ChildComponent func = {testFunc} />

In the ChildComponent.js you can callback this function like this this.props.func()

Please try this. Remove brackets while calling testFunc because of javascript syntax.

export default class Parent extends Component {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM