React Native this2.'function' is not a function

后端 未结 2 651
小鲜肉
小鲜肉 2021-01-23 19:24

I have a problem with my React Native Component.

sayHi = (s) => {
    console.log(\'hey\' + s)
}

renderListItem(item, i) {

    return (
        

        
2条回答
  •  轮回少年
    2021-01-23 20:04

    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 to map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this 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.

提交回复
热议问题