You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Antd Select组件如何实现下拉选项与输入框显示不同内容?

解决方案

要实现选中后输入框显示国家代码、下拉选项保持「代码+名称」的展示,只需调整以下几个核心点:

  1. 替换Option的绑定值:把原来绑定的country.name改成country.code,让Select选中后默认显示code值
  2. 修正默认值:原默认值"Japan"替换为对应国家的代码"+987"
  3. 同步回调逻辑:handleChange接收的参数现在是国家代码,对应调整日志输出即可

修改后的完整代码如下:

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 country code: ${value}`);
};

const App: React.FC = () => (
  <>
    <Select defaultValue="+987" onChange={handleChange}>
      {countryNames.map((country) => (
        <Option key={country.code} value={country.code}>
          {`${country.code} ${country.name}`}
        </Option>
      ))}
    </Select>
  </>
);

export default App;

补充说明

如果业务需要同时获取国家名称和代码(比如提交表单时需两个字段),可以给Select添加labelInValue属性,此时handleChange会接收包含value(code)和label(下拉显示文本)的对象,示例如下:

// 开启labelInValue属性
<Select 
  defaultValue={{ value: "+987", label: "+987 Japan" }} 
  onChange={handleChange} 
  labelInValue
>
  {countryNames.map((country) => (
    <Option key={country.code} value={country.code}>
      {`${country.code} ${country.name}`}
    </Option>
  ))}
</Select>

// 对应的回调函数
const handleChange = (option: { value: string; label: string }) => {
  console.log(`selected code: ${option.value}, selected label: ${option.label}`);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:50:25