You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将FlatList中组件的GameId传入指定处理函数?

解决FlatList中传递指定Item的GameId给点击函数的问题

核心问题修正步骤:

  • 修正renderItem方法:在渲染列表项时,根据GameId判断是否显示按钮,并将当前item的GameId传入handlePress

    renderItem = ({ 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}
    />
    

关键说明:

  1. 每个列表项的GameId属于当前item,而非组件实例属性,因此不能通过this.GameId获取,必须从renderItem的item参数中传递
  2. 若需要给多个不同GameId的项添加按钮,可修改条件判断为[1,3,5].includes(item.GameId)这类形式匹配多个值

内容的提问来源于stack exchange,提问作者SHEHARYAR AFTAB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:30:55