React Native this2.'function' is not a function

后端 未结 2 624
小鲜肉
小鲜肉 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 19:54

    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))}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题