【问题标题】:How to leave the values already selected inside the Select and MenuItem?如何在 Select 和 MenuItem 中保留已选择的值?
【发布时间】:2020-12-28 21:08:37
【问题描述】:

我是 ReactJS 的初学者,但我对 Selects 有疑问。我有一个Select,它用MenuItem 渲染一些植物和蜜蜂。

我需要的是 Select 已经带有一些在 beesplants 列表中标记的值。

如果用户单击新属性,则选择为空白,但用户单击任何要编辑的属性,则必须将选择标记为选中。

我希望我能够正确解释它。这是我输入CodeSandBox的代码

这是我的蜜蜂数据库的模拟:

{
  "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)"
      }
    }
  ]
}

这是我的植物数据库的模拟:

{
  "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"
      }
    }
  ]
}

这是我的属性数据库的模拟:

  {
    "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)"
          }
        ]
      ]
    }
  }

【问题讨论】:

    标签: javascript reactjs react-material


    【解决方案1】:

    如果我理解正确,问题是选择有 [Object object] 而不是实际标签。

    如果是这样,问题是下拉列表期望获得value 属性的字符串数组。意味着beeSelect应该是一个字符串数组,但它实际上是一个蜜蜂(数组)数组

    例如

    "accepted-bees": [
      [
        {
          "id": 46,
          "kind": "Africanizada (Apis mellifera)"
        }
      ]
    ]
    

    所以,.map 看起来应该有点不同

    const _selectedBees = item.attributes["accepted-bees"].map((bee) => bee[0].kind);
    

    (植物也是如此)

    https://codesandbox.io/s/edit-modal-working-forked-of675?file=/src/features/components/dialog-property/DialogProperty.jsx:1580-1673

    注意事项:

    1. 为什么accepted-bees 是一个数组数组,如果它只有一个项目(子数组)
    2. .map((bee) => bee) 没有意义。它返回与获得的值相同的值。

    【讨论】:

    • 嘿 Mosh,这对我来说非常有效。谢谢!!!
    • 我的荣幸 :) 祝你好运。
    猜你喜欢
    • 2020-11-29
    • 2019-01-11
    • 1970-01-01
    • 2014-09-17
    • 2018-11-15
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多