如何将FlatList中组件的GameId传入指定处理函数?
解决FlatList中传递指定Item的GameId给点击函数的问题
核心问题修正步骤:
修正
renderItem方法:在渲染列表项时,根据GameId判断是否显示按钮,并将当前item的GameId传入handlePressrenderItem = ({ item }) => { return ( <View> {/* 列表项原有内容 */} <Text>{item.GameId}</Text> {/* 仅在目标GameId的项显示按钮,这里以GameId=1为例 */} {item.GameId === 1 && ( <Button title="操作按钮" onPress={() => this.handlePress(item.GameId)} /> )} </View> ); };修改
handlePress函数:接收gameId参数,替代原本错误的this.GameId引用handlePress = (gameId) => { if (gameId === 1) { this.setState({ btnvalue1: 'flex' }); console.log('ssss11'); } else { this.setState({ btnvalue1: 'none' }); } };清理FlatList无效配置:移除FlatList中多余的
handlePress属性(FlatList本身不支持该props)<FlatList data={this.state.dataSource} renderItem={this.renderItem} keyExtractor={item => item.GameId.toString()} ItemSeparatorComponent={this.renderSeprator} refreshing={this.state.refreshing} onRefresh={this.handleRefresh} />
关键说明:
- 每个列表项的
GameId属于当前item,而非组件实例属性,因此不能通过this.GameId获取,必须从renderItem的item参数中传递 - 若需要给多个不同
GameId的项添加按钮,可修改条件判断为[1,3,5].includes(item.GameId)这类形式匹配多个值
内容的提问来源于stack exchange,提问作者SHEHARYAR AFTAB
相关产品推荐
相关产品推荐

