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
相关产品推荐
相关产品推荐

