React中如何获取选中选项所属optgroup的信息?
解决方法
首先得修正你的select结构——目前reserveOptions和firstTeamOptions是放在对应optgroup标签外面的,这会导致这些选项不属于任何分组,根本拿不到分组信息。先把动态选项移到对应的optgroup内部:
<div className=""> <select onChange={(e) => { // 获取选中的option元素 const selectedOption = e.target.options[e.target.selectedIndex]; // 获取所属的optgroup const optgroup = selectedOption.parentElement; // 初始化分组名称 let groupName = null; // 判断当前选项是否在optgroup内 if (optgroup.tagName === 'OPTGROUP') { groupName = optgroup.label; } // 输出结果 console.log('选中值:', e.target.value); console.log('所属分组:', groupName); }} className=" bg-gray-500" > <option>Pick Player</option> <optgroup label="Substitutes">{subOptions}</optgroup> <optgroup label="Reserves">{reserveOptions}</optgroup> <optgroup label="First Team">{firstTeamOptions}</optgroup> <optgroup label=""></optgroup> <option>+ Add Player</option> </select> </div>
关键步骤说明:
- 通过
e.target.selectedIndex拿到选中项在options列表里的索引 - 用
e.target.options[index]获取到具体的option DOM元素 - 调用
option.parentElement得到它的父元素,也就是对应的optgroup - 判断父元素是否是optgroup(避免像"Pick Player"这种顶级选项报错),如果是就取它的
label属性
这样就能同时获取选中值和所属的分组名称了。
内容的提问来源于stack exchange,提问作者Stanisloth
相关产品推荐
相关产品推荐

