AntD Select 中的选定值

huangapple go评论67阅读模式
英文:

Selected value in AntD Select

问题

我正在使用AntD选择组件,如附图所示,选择其任何选项时,AntD选择会显示“id”而不是“name”。是否有解决方法?

const MyComponent = () => {
    const data = [
      {
        id: "5c83c2d0-e422-4eb6-b2cb-02fe60045e6e",
        name: "Item 1"
      },
      {
        id: "1b9175f9-750a-48c1-bbf7-0ff9a2fde7da",
        name: "Item 2"
      }
    ];

    return (
       <Select>
            {data.map((item) => (
                <Option value={item.id} key={item.id}>{item.name}</Option>
            )}
       </Select>
    );
};

AntD Select 中的选定值

英文:

I'm using the AntD select component, and as you can see in the attached image, when selecting any of its options, AntD select displays "id" rather than "name." Is there a fix for this?

const MyComponent = () =&gt; {
    const data = [
      {
        id: &quot;5c83c2d0-e422-4eb6-b2cb-02fe60045e6e&quot;
        name: &quot;Item 1&quot;
      },
      {
        id: &quot;1b9175f9-750a-48c1-bbf7-0ff9a2fde7da&quot;
        name: &quot;Item 2&quot;
      }
    ];

    return (
       &lt;Select&gt;
            {data.map((item) =&gt; (
                &lt;Option value={item.id} key={item.id}&gt;{item.name}&lt;/Option&gt;
            )}
       &lt;/Select&gt;
    );
};

AntD Select 中的选定值

答案1

得分: 1

Ant Design<Option> 组件具有一个名为 label 的属性,用于更改显示的文本。

所以,不要将 item.name 作为子组件传递,而是将其作为 label 属性传递:

return (
   <Select>
        {data.map(item => (
            <Option value={item.id} key={item.id} label={item.name} />
        )}
   </Select>
);
英文:

The Ant design &lt;Option&gt; has a prop named label to alter the shown text.

So instead of passing item.name as a child components, pass it as the label prop:

return (
   &lt;Select&gt;
        {data.map(item =&gt; (
            &lt;Option value={item.id} key={item.id} label={item.name} /&gt;
        )}
   &lt;/Select&gt;
);

huangapple
  • 本文由 发表于 2023年2月14日 22:09:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75449018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定