javascript - 如何在反应js中获取所选选项的ID
问题描述
我创建了一个非常简单的选择框。
<FormGroup>
<label for='category' className='label'>Category</label>
<select ref="categoryName">
{categoriesList}
</select>
</FormGroup>
和
let categoriesList = categories.map(category =>
<option id={category.id}>
{category.type}
</option>
)
我试图弄清楚如何获取在下拉列表中选择的选项的 'id' 属性的值,我想使用该值进行进一步处理。请指教。谢谢
解决方案
您可以将onChange
事件处理程序添加到检查所选索引并从所选选项中检索 id 的 select 中。
onChangeHandler = (e) => {
const index = e.target.selectedIndex;
const el = e.target.childNodes[index]
const option = el.getAttribute('id');
}
<FormGroup>
<label for='category' className='label'>Category</label>
<select onChange={onChangeHandler}>
{categories.map(category =>
<option id={category.id}>
{category.type}
</option>
)}
</select>
</FormGroup>
推荐阅读
- validation - Magnolia 现场检查验证
- python - Beautifulsoup .text 函数不返回文本
- javascript - LitElement 的多个类继承
- node.js - 有没有办法在 redis 服务的 GEOADD 方法中添加 Date 属性
- typeclass - 类金刚石界面约束问题
- python - 在 EPS 图像中存储 DPI 信息
- php - 在本地主机上运行 laravel 时出现内部服务器错误
- linux - 期望工具和逻辑或
- python - 使用 IF 和 Apply 函数创建新列
- ios - Swift4:致命错误:在展开可选值时意外发现 nil