首页 > 解决方案 > 如何在 onPress 中获取元素键而不在 React Native 中绑定

问题描述

我们已经知道 AirBnB 风格指南不鼓励在渲染函数 ( source ) 中使用 .bind( )。如此处所述:

JSX 道具中的绑定调用或箭头函数将在每个渲染上创建一个全新的函数。这对性能不利,因为它会导致垃圾收集器被调用的方式超出必要的程度。

这是我们以前做的,将参数传递给 bind

renderSingleItem = ({item}) => <TouchableOpacity onPress={func.bind(this, item.id)}> return <FlatList data={data} renderItem={this.renderSingleItem}/>

这似乎是唯一的方法,因为 React Native 中的 onPress 参数不包含像 ReactJS 那样的目标对象。

反应JS:

typeof event.taget === 'object'

反应原生:

typeof event.taget === 'number'

有更好的方法吗?

标签: react-native

解决方案


You can use,

renderSingleItem = ({item}) => <TouchableOpacity onPress={() =>
  this.func(item.id)
}>

推荐阅读