React Native Elements中如何从嵌套ListItem获取用户ID?
解决React Native FlatList列表项点击获取用户ID的问题
我来帮你搞定这个获取用户ID的问题!你遇到的问题主要有两个核心原因:FlatList的renderItem参数解构错误,以及事件绑定的方式不对,咱们一步步修正:
首先修正最关键的renderItem参数问题
你之前写的renderItem={({user,index}) => (...)}是错误的,FlatList的renderItem回调接收的参数对象里,当前列表项的数据属性是item,不是user。正确的写法是把item重命名为user,这样才能拿到正确的用户数据:
renderItem={({ item: user, index }) => ( // 这里的user才是当前列表项的用户数据 )}
正确的点击事件绑定方式
之前你直接写onPress={this.gotoDetail(user.id)}会导致组件渲染时就立刻执行gotoDetail函数,而不是点击时触发。下面两种方法都能解决这个问题:
方法1:用箭头函数包裹(最直观推荐)
在onPress和onPressRightIcon里用箭头函数包裹,点击时才调用gotoDetail并传入用户ID:
<ListItem title={`${user.lastname}, ${user.firstname}`} titleStyle={{fontWeight:'bold', color: white}} chevronColor={black} key={index} rightIcon={{style:{fontSize:28, color:white}}} onPress={() => this.gotoDetail(user.id)} onPressRightIcon={() => this.gotoDetail(user.id)} /> // 对应的事件处理函数 gotoDetail = (userId) => { console.log('当前点击的用户ID:', userId); }
方法2:用bind绑定参数
如果你习惯用bind的方式,也可以这样写:
<ListItem // 其他属性不变 onPress={this.gotoDetail.bind(this, user.id)} onPressRightIcon={this.gotoDetail.bind(this, user.id)} /> // 事件处理函数同样接收userId gotoDetail = (userId) => { console.log('当前点击的用户ID:', userId); }
为什么你之前的尝试都失败了?
- React Native的事件机制和Web不同:RN的组件不是DOM元素,事件对象里没有
e.target.value或e.target.id这类属性,所以没法通过这种方式获取ID。 this.id/this.value无效:事件处理函数里的this指向的是组件实例,不是点击的列表项,自然拿不到当前item的ID。- refs不适合这种场景:列表里有大量动态生成的项,refs很难精准定位到点击的那个item,不是最优解。
完整修正后的代码
<List> {users !== '' && ( <FlatList data={users} keyExtractor={user => user.id.toString()} // 建议把ID转成字符串,符合React的key要求 renderItem={({ item: user, index }) => ( <ListItem title={`${user.lastname}, ${user.firstname}`} titleStyle={{fontWeight:'bold', color: white}} chevronColor={black} key={index} rightIcon={{style:{fontSize:28, color:white}}} onPress={() => this.gotoDetail(user.id)} onPressRightIcon={() => this.gotoDetail(user.id)} /> )} /> )} </List> // 事件处理函数 gotoDetail = (userId) => { console.log('用户ID:', userId); }
内容的提问来源于stack exchange,提问作者Edper
相关产品推荐
相关产品推荐

