代码之家  ›  专栏  ›  技术社区  ›  CCCC

Antd Select-如何在下拉列表和输入字段中显示不同的值

  •  0
  • CCCC  · 技术社区  · 2 年前

    当前UI

    enter image description here

    预期行为 enter image description here

    我该怎么做?

    应用.tsx

    import React from "react";
    import "./index.css";
    import { Select } from "antd";
    
    const { Option } = Select;
    
    const countryNames = [
      {
        name: "Japan",
        code: "+987"
      },
      {
        name: "aVeryVeryVeryVeryLongCountryName",
        code: "+123"
      }
    ];
    
    const handleChange = (value: string) => {
      console.log(`selected ${value}`);
    };
    
    const App: React.FC = () => (
      <>
        <Select defaultValue="Japan" onChange={handleChange}>
          {countryNames.map((country) => (
            <Option key={country.name} value={country.name}>
              {`${country.code} ${country.name}`}
            </Option>
          ))}
        </Select>
      </>
    );
    
    export default App;
    

    Codesandbox
    https://codesandbox.io/s/basic-usage-antd-5-1-5-forked-mfw8fj?file=/demo.tsx

    1 回复  |  直到 2 年前
        1
  •  2
  •   John Li    2 年前

    根据 antd document , Select 可以从中指定标签值 Option 道具 optionLabelProp ,在本用例中可以从中获取值 country.code .

    用于扩展的大小 选项 基于其内容, dropdownMatchSelectWidth 可以设置 false ,因此 选项 不限于的大小 选择 .

    修改了演示: codesandbox

    <Select
      defaultValue="Japan"
      onChange={handleChange}
      // 👇 Specify label prop here
      optionLabelProp="label"
      // 👇 Set Option to be extendable by content here
      dropdownMatchSelectWidth={false}
    >
      {countryNames.map((country) => (
        <Option
          key={country.name}
          value={country.name}
          // 👇 Give label value for Select here
          label={country.code}
        >
          {`${country.code} ${country.name}`}
        </Option>
      ))}
    </Select>