关于react-native中FlatList的 this指向问题

版权声明:原创文章,未经允许不得转载!!! https://blog.csdn.net/halo1416/article/details/81746375

问题描述:在使用 FlatList 制作列表过程中,其 renderItem 属性返回的是一个 TouchableOpacity 的按钮,但是在触发其点击事件onPress时,总是报错!

FlatList代码:

_renderItem渲染item的代码:

报错原因:

TouchableOpacity的onPress中使用了this,但他是不存在的,应用在FlatList的 renderItem 属性在调用 _renderItem 方法时并没有this指向。

解决方法1:  

        renderItem = {this._renderItem.bind(this)}

解决方法2:

        renderItem = {(item,index) => this._renderItem(item)}

===>>> 其余地方不变即可!

注意: renderItem = {this._renderItem}时默认传 一个解构出来的item(包括了item和separators两个Object 和index一个变量),所以在  _renderItem 方法中还需要解构一次才行!!!

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出

对博客文章的参考,若原文章博主介意,请联系删除!请原谅

猜你喜欢

转载自blog.csdn.net/halo1416/article/details/81746375