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

utugiqy6  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(576)

当前用户界面

预期行为

我该怎么做呢?
App.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;

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

iyzzxitl

iyzzxitl1#

根据antddocumentSelect可以使用optionLabelPropOption属性中指定标签值,在此用例中,optionLabelProp可以从country.code中获取值。
为了根据Option的内容扩展其大小,可以将dropdownMatchSelectWidth设置为false,从而使Option不限于Select的大小。
修改演示日期: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>

相关问题