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

ReactJS中如何获取select下拉框option的title属性值并设置useState

实现方案

方案一(更推荐,不依赖DOM属性,数据稳定性更高)

直接在onChange事件中通过选中的国家名称,匹配countryList数组拿到对应国家的code,同时给两个state赋值即可,不需要额外读取title属性:

// 先修正你原代码里countryList漏写的闭合方括号
export const countryList =[ 
    {name: 'Afghanistan', code: 'AF'}, 
    {name: 'Åland Islands', code: 'AX'}, 
    {name: 'Albania', code: 'AL'}, 
    {name: 'Algeria', code: 'DZ'}, 
    {name: 'American Samoa', code: 'AS'},
    // 其余国家项
]

const [collcountry,setCollCountry] = useState("");
const [collcountrycode,setCollCountryCode] = useState("");

<Form.Select 
  aria-label="Select Country"  
  onChange={(e)=> { 
    const selectedName = e.target.value
    setCollCountry(selectedName)
    // 匹配对应的国家项获取code
    const matchedCountry = countryList.find(item => item.name === selectedName)
    matchedCountry && setCollCountryCode(matchedCountry.code)
  }} 
>
  <option value=""></option>
  {countryList.map((item, index) => (
    <option key={index} value={item.name}>{item.name}</option>
  ))}                                              
</Form.Select>

方案二(直接读取title属性实现)

如果你确实需要从option的title属性取code,可以通过selectedOptions拿到当前选中的option节点,再读取title属性赋值:

<Form.Select 
  aria-label="Select Country"  
  onChange={(e)=> { 
    setCollCountry(e.target.value)
    // 获取选中的option元素,读取title属性
    const selectedOption = e.target.selectedOptions[0]
    setCollCountryCode(selectedOption.title)
  }} 
>
  <option value=""></option>
  {countryList.map((item, index) => (
    <option key={index} title={item.code} value={item.name}>{item.name}</option>
  ))}                                              
</Form.Select>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:39:03