I have two different components: MyComponent
and BookDisplay
MyComponent
class MyComponent extends Component {
constructor() {
super()
this.state = {
book: "A"
}
}
updateBook() {
this.setState({book: "B"})
}
render() {
const {book} = this.state
return (
<BookDisplay updateBook = {() => this.updateBook()} book={book} />
)
}
}
BookDisplay
const BookDisplay = ({book, updateBook}) => {
return (
<View>
<Text onPress = {updateBook} >
{book}
</Text>
</View>
)
}
What I'm currently stuck on after going through various JS, react, and react-native resources is trying to understand the one line calling updateBook on the BookDisplay
component
<BookDisplay updateBook={() => this.updateBook()} ... />
Is this written in this manner because updateBook is a function defined in MyComponent
and this is how we assign a prop a function? Why is it not updateBook={this.updateBook()}
instead?
Thanks!
Here you are passing a function to the updateBook prop:
<BookDisplay updateBook={() => this.updateBook()} ... />
But here you are executing the function and passing the result of that function:
<BookDisplay updateBook={ this.updateBook()} ... />
The arrow function also binds the this
object to MyComponent
.
Inside the BookDisplay
in some point will try to execute his updateBook
prop and it is going to be your function