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

React Native中从JSON填充SelectDropdown下拉菜单遇问题求助

React Native 下拉菜单加载本地JSON数据解决方案

问题原因

SelectDropdown 的 data 属性接受字符串/数字类型的数组,你之前直接通过 map 返回 <Text> 组件,组件会将每个元素识别为对象,因此显示 [object Object]。

正确实现代码

方式1:提取纯字符串数组(最简洁)

先从JSON数据中提取 Location 字段,生成纯字符串数组后传给组件:

// 处理JSON数据,提取Location字段组成数组
const locationOptions = crimeJSON.map(record => record.Location);

然后将数组传入 SelectDropdown:

<SelectDropdown
  data={locationOptions}
  onSelect={(selectedItem, index) => {
    // 选中选项后的逻辑,比如打印选中值
    console.log('选中的地点:', selectedItem);
  }}
  buttonTextAfterSelection={(selectedItem) => selectedItem}
  rowTextForSelection={(item) => item}
/>

方式2:自定义选项UI(保留原始数据)

如果需要自定义选项的样式或展示更多内容,可以直接传入原始JSON数组,通过组件的回调属性指定显示字段,并自定义选项渲染:

<SelectDropdown
  data={crimeJSON}
  onSelect={(selectedItem) => {
    // 选中后可直接访问原始数据的所有字段
    console.log('选中的完整数据:', selectedItem);
  }}
  // 按钮选中后显示的文本
  buttonTextAfterSelection={(selectedItem) => selectedItem.Location}
  // 下拉列表中每个选项显示的文本
  rowTextForSelection={(item) => item.Location}
  // 自定义选项的UI样式
  renderCustomizedRow={(item) => (
    <Text style={{ paddingVertical: 10, paddingHorizontal: 15, color: '#222' }}>
      {item.Location}
    </Text>
  )}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:34:53