react-native - react native 报 Cannot read property 'bind' of undefined

查看:1774
本文介绍了react-native - react native 报 Cannot read property 'bind' of undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

先上代码

    //渲染行组件
    _renderRow(rowData) {
        return (
            <TouchableOpacity onPress={this.show.bind(this)}>
                <View style={styles.row}>
                    <Image style={styles.thumb} source={{uri: rowData.posters.thumbnail}}/>
                    <View style={styles.rightBox}>
                        <Text style={styles.title} numberOfLines={2}>{rowData.title}</Text>
                        <Text style={styles.subtitle}>上映时间:{rowData.year}</Text>
                        <Text style={styles.subtitle}>影长:{rowData.runtime}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

我给了个onPress绑定点击事件
一加上直接就报错了

不知道什么原因!我看官方文档也是 onPress 绑定了个方法呀
我用匿名方法能正常弹内容呢!

            <TouchableOpacity onPress={() => {
                alert(rowData.title)
            }}>

解决方案

首先提示的很清楚 this.showundefined,然后帮你分析下原因:

  1. 组件里确实没有 show 方法(这个应该不太可能)

  2. this 并不是指向此组件的实例,比如 renderRow={this._renderRow}

最后你觉得下列有什么区别?

// 第一种
renderRow={this._renderRow}
// 第二种
renderRow={(row) => this._renderRow(row)}
// 第三种
renderRow={this._renderRow.bind(this)}
// 第四种
const _renderRow = (row) => { this.show() };
...
renderRow={_renderRow}

这篇关于react-native - react native 报 Cannot read property &#039;bind&#039; of undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆