首页 > 解决方案 > 如何在反应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' 属性的值,我想使用该值进行进一步处理。请指教。谢谢

标签: javascripthtmlreactjs

解决方案


您可以将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>

推荐阅读