Antd Select组件如何实现下拉选项与输入框显示不同内容?
解决方案
要实现选中后输入框显示国家代码、下拉选项保持「代码+名称」的展示,只需调整以下几个核心点:
- 替换Option的绑定值:把原来绑定的
country.name改成country.code,让Select选中后默认显示code值 - 修正默认值:原默认值
"Japan"替换为对应国家的代码"+987" - 同步回调逻辑:
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
相关产品推荐
相关产品推荐

