I have a problem with my React Native Component.
sayHi = (s) => {
console.log(\'hey\' + s)
}
renderListItem(item, i) {
return (
Just for reference, the bind
solution mentioned in the comments by Andrew Li can be accomplished by changing this line
{list.map(this.renderListItem)}
to this
{list.map(this.renderListItem.bind(this))}
Array#map executes the callback in a different context so this
isn't correctly bound. Per the documentation:
Syntax
var new_array = arr.map(callback[, thisArg])
Parameters
[...]
thisArg
Optional. Value to use as
this
when executing callback.[...]
If a
thisArg
parameter is provided tomap
, it will be used as callback'sthis
value. Otherwise, the valueundefined
will be used as itsthis
value.
You can pass this
context as the second argument to Array#map
:
{list.map(this.renderListItem, this)}
Or, use Function#bind
directly:
{list.map(this.renderListItem.bind(this))}
Finally, you could use an arrow function:
{list.map((item, i) => this.renderListItem(item, i))}
Though I would choose the first option personally.