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

React Native点击按钮时如何获取对象数组中的对应ID值?

问题

我通过map和Object.entries渲染了每个公司名称作为按钮,但当前点击按钮时只会弹出“Simple Button pressed”的提示。我希望点击按钮时,提示框能显示对应公司的ID(比如点击Company 1按钮时显示ID 4),请问该怎么实现?

原代码如下:

const companyDatas = {
  "accounts": {
      "company 1 ": {
          "id": "4",
          "enabled": "1"
      },
      "company 2": {
          "id": "2",
          "enabled": "1"
      },
      "company 3": {
          "id": "1",
          "enabled": "1"
      }
  }
};

const [companyData, setCompanyData] = useState(companyDatas)

return (
  <View style={styles.container}>
    {
      Object.entries(companyData.accounts)
      .map(([company, accountData]) => (
        <View key={company}>

      <Button
         title={company}
         onPress={() => Alert.alert('Simple Button pressed')}
     />
          
        </View>
      ))
    }
  </View>
);
}

输出效果:
输出效果

解决方案

只需要修改Button组件的onPress回调函数,把提示内容替换成当前公司对应的ID即可。在map遍历的过程中,我们已经通过解构拿到了每个公司的accountData对象,里面包含了id字段,直接使用这个字段就行。

修改后的完整代码:

const companyDatas = {
  "accounts": {
      "company 1 ": {
          "id": "4",
          "enabled": "1"
      },
      "company 2": {
          "id": "2",
          "enabled": "1"
      },
      "company 3": {
          "id": "1",
          "enabled": "1"
      }
  }
};

const [companyData, setCompanyData] = useState(companyDatas)

return (
  <View style={styles.container}>
    {
      Object.entries(companyData.accounts)
      .map(([company, accountData]) => (
        <View key={company}>
          <Button
            title={company}
            // 替换提示内容为对应公司的ID
            onPress={() => Alert.alert(`公司ID:${accountData.id}`)}
          />
        </View>
      ))
    }
  </View>
);
}

这样修改后,点击任意公司按钮,提示框就会显示该公司对应的ID了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 04:40:54