最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Native this2.'function' is not a function - Stack Overflow

programmeradmin2浏览0评论

I have a problem with my React Native Component.

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

renderListItem(item, i) {

    return (
        <TouchableOpacity
            key={i}
            style={styles.listItem}
            onPress={() => { this.sayHi('bob') }}>

        <Text>{item}</Text>
        </TouchableOpacity>
    )
}

render() {
    this.sayHi('patrick')

    const { list } = this.props

    return (
        <View>
        {list.map(this.renderListItem)}
        </View>
    )
}

In renderListItem I get an error _this2.sayHi is not a function.

Searched online but most posts do not fit my situation; I took a look at this post but I already have an arrow function so it's not a context problem.

The function console logs just fine in the render(). I tried to bind the this in the constructor but I still get the error.

I have a problem with my React Native Component.

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

renderListItem(item, i) {

    return (
        <TouchableOpacity
            key={i}
            style={styles.listItem}
            onPress={() => { this.sayHi('bob') }}>

        <Text>{item}</Text>
        </TouchableOpacity>
    )
}

render() {
    this.sayHi('patrick')

    const { list } = this.props

    return (
        <View>
        {list.map(this.renderListItem)}
        </View>
    )
}

In renderListItem I get an error _this2.sayHi is not a function.

Searched online but most posts do not fit my situation; I took a look at this post but I already have an arrow function so it's not a context problem.

The function console logs just fine in the render(). I tried to bind the this in the constructor but I still get the error.

Share Improve this question asked Jun 3, 2017 at 0:40 FrenchMajestyFrenchMajesty 1,1592 gold badges16 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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.

Just for reference, the bind solution mentioned in the ments by Andrew Li can be acplished by changing this line

{list.map(this.renderListItem)}

to this

{list.map(this.renderListItem.bind(this))}
发布评论

评论列表(0)

  1. 暂无评论