我们已经知道,AirBnB样式指南不鼓励在渲染函数(source)中使用.bind()。如here所述:
JSX prop中的绑定调用或箭头函数将在每个渲染器上创建一个全新的函数。这会降低性能,因为这将导致以不必要的方式调用垃圾回收器。
这是我们过去所做的,将参数传递给bind
renderSingleItem = ({item}) => <TouchableOpacity onPress={func.bind(this, item.id)}>
return <FlatList data={data} renderItem={this.renderSingleItem}/>
这似乎是唯一的方法,因为React Native中onPress的参数不像ReactJS那样包含目标对象。
ReactJS:
typeof event.taget === 'object'
反应原生:
typeof event.taget === 'number'
有更好的方法吗?
答案 0 :(得分:0)
您始终可以使用记忆力并执行
<TouchableOpacity key={article.id} onPress={this.goToArticle(article.id)}>
以及您的goToArticle
方法中
goToArticle = (articleId) => e => { // ... e are the native events for touch
console.log(articleId)
}
答案 1 :(得分:0)
您可以使用
renderSingleItem = ({item}) => <TouchableOpacity onPress={() =>
this.func(item.id)
}>