Reputation: 1623
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?
Upvotes: 1
Views: 51
Reputation: 33974
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 :)
Upvotes: 1