You need to enable JavaScript to run this app. ReactJS中如何让Select组件保留并回显已选中的MenuItem选项
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何让Select组件保留并回显已选中的MenuItem选项

React Select 组件适配新增/编辑场景的选中状态匹配问题

我是一名ReactJS初学者,在使用Select组件搭配MenuItem渲染蜜蜂、植物选项时遇到了开发障碍。

功能需求

Select组件需要在选项列表中自动标记已选中的内容,覆盖两类交互场景:

  • 触发「新增属性」操作时,两个Select组件保持空白的无选中初始状态
  • 点击已有属性进入编辑状态时,两个Select组件需要自动匹配、标记出该属性关联的已选蜜蜂、植物选项
    已整理出对应的实现逻辑与配套模拟数据,如下:

配套模拟数据

  1. 蜜蜂数据库模拟结构
{
  "data": [
    {
      "id": "1",
      "type": "bee-databases",
      "attributes": {
        "species-name": "Africanizada (Apis mellifera)"
      }
    },
    {
      "id": "2",
      "type": "bee-databases",
      "attributes": {
        "species-name": "Abelha-cachorro, Arapuá, Irapuá (Trigona spinipes)"
      }
    },
    {
      "id": "3",
      "type": "bee-databases",
      "attributes": {
        "species-name": "Andorinha, Benjoi (Scaptotrigona polysticta)"
      }
    }
  ]
}
  1. 植物数据库模拟结构
{
  "data": [
    {
      "id": "1",
      "type": "plant-databases",
      "attributes": {
        "species-name": "Cana-de-açucar"
      }
    },
    {
      "id": "2",
      "type": "plant-databases",
      "attributes": {
        "species-name": "Citros"
      }
    },
    {
      "id": "3",
      "type": "plant-databases",
      "attributes": {
        "species-name": "Eucalipto"
      }
    }
  ]
}
  1. 属性数据库模拟结构
{
  "id": "45",
  "type": "properties",
  "attributes": {
    "farmer-name": "João Galli",
    "name": "Nova Propriedade",
    "address": "Rua teste",
    "total-planted-area": "100",
    "total-forest-area": "40",
    "apiaries-in-use": 20,
    "plants": [
      [
        {
          "id": 46,
          "kind": "Cana-de-açucar"
        }
      ]
    ],
    "accepted-bees": [
      [
        {
          "id": 46,
          "kind": "Africanizada (Apis mellifera)"
        }
      ]
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 21:45:03