简体   繁体   中英

How to pass info from a child component to a function in the parent component? (REACT NATIVE)

I have a presentational child component with 10 buttons like so

  <Button onPress={...} title="1" />
  <Button onPress={...} title="2" />
  <Button onPress={...} title="3" />
  ...

I have a function in the parent component that needs to know the number of each button.

checkNumber(e) {
  ...
  return number
}

How do I get the number from the child component's button without writing 10 functions?

You are looking for a concept called callbacks in React or react-native

You will have event handler function in parent component. If your event handler function is a regular function then you make sure you bind it in constructor or change it to an arrow function

Since you are using normal function you need binding in constructor like

  constructor(props){
      super(props);
      this.checkNumber = this.checkNumber.bind(this);
  }

  checkNumber(e, number){
       ...
     return number
   }

Or use an arrow function. You no need to bind it manually in constructor

  checkNumber = (e, number) => {
       ...
     return number
   }

Now pass down checkNumber function as a prop to your presentional component like

    <PresentationalComponent checkNumber={this.checkNumber} />

And in your presentational component

     <Button  onPress={e => this.props.checkNumber(e, 1)} title=“1”/>
    <Button onPress={e => this.props.checkNumber(e, 2)} title="2" />
      .......
      .......
      <Button onPress={e => this.props.checkNumber(e, 10)} title="10”/>

Please excuse me if there are any typo error because I am answering in my mobile :)

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