React中如何将Select选项的ID存入状态?
解决React中Select组件同时保存选中项的value和id问题
你的问题出在event.target指向的是<select>元素本身,而非选中的<option>,所以event.target.id获取的是select标签上的id,不是选中选项的id。这里提供两种可行的解决方法:
方法一:通过选中值匹配原数据获取id
利用选中的value在hologram数组中找到对应的选项对象,从中提取id:
const [value, setValue] = React.useState(''); const [id, setId] = React.useState(''); const handleChange = (event) => { const selectedValue = event.target.value; setValue(selectedValue); // 从数据源匹配对应选项 const matchedOption = hologram.find(opt => opt.path === selectedValue); if (matchedOption) { setId(matchedOption.id); } }; // select标签的id属性无需绑定状态id,可移除或设置固定值 <select value={value} onChange={handleChange}> {hologram.map((option) => ( <option key={option.id} value={option.path}>{option.denomination}</option> ))} </select>
方法二:利用dataset属性存储id
给<option>添加data-id属性存储id,通过selectedOptions获取选中的option元素,读取其dataset值:
const [value, setValue] = React.useState(''); const [id, setId] = React.useState(''); const handleChange = (event) => { setValue(event.target.value); // 获取选中的option元素 const selectedOpt = event.target.selectedOptions[0]; if (selectedOpt) { setId(selectedOpt.dataset.id); } }; <select value={value} onChange={handleChange}> {hologram.map((option) => ( <option key={option.id} data-id={option.id} value={option.path}>{option.denomination}</option> ))} </select>
另外建议给每个option添加key属性(用option.id即可),符合React列表渲染的规范。
内容的提问来源于stack exchange,提问作者alex morales
相关产品推荐
相关产品推荐

