猿问

如何在 React 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”属性值,我想使用此值进行进一步处理。请指教。谢谢


慕姐8265434
浏览 189回答 2
2回答

缥缈止盈

您可以将onChange事件处理程序添加到 select 以检查所选索引并从所选选项中检索 id。onChangeHandler = (e) => {&nbsp; const index = e.target.selectedIndex;&nbsp; const el = e.target.childNodes[index]&nbsp; const option =&nbsp; el.getAttribute('id');&nbsp;&nbsp;}<FormGroup>&nbsp; <label for='category' className='label'>Category</label>&nbsp; <select onChange={onChangeHandler}>&nbsp; &nbsp; &nbsp; {categories.map(category =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option id={category.id}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{category.type}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </option>&nbsp; &nbsp; &nbsp; )}&nbsp; </select></FormGroup>

HUWWW

理想情况下,您应该尽量避免从 DOM 获取状态。如果你控制状态,让 React 来渲染你的状态,React 工作得很好。下面是一个简单的例子,基本上我所做的就是将状态索引存储到一个数组中。当我更新它时,React 视图将相应地更新。你如何存储状态完全取决于你,而不是 DOM。const {useState} = React;const lookup = [&nbsp; {id: 1, value: 'one'},&nbsp; {id: 2, value: 'two'},&nbsp; {id: 3, value: 'three'}];function List() {&nbsp; const [selected, setSelected] = useState(-1);&nbsp;&nbsp; const value = selected !== -1 && lookup[selected];&nbsp; return <div>&nbsp; &nbsp; <select&nbsp;&nbsp; &nbsp; &nbsp; onChange={(e) => setSelected(e.target.value)}&nbsp; &nbsp; &nbsp; value={selected}>&nbsp; &nbsp; &nbsp; <option>Please Selected an option</option>&nbsp; &nbsp; &nbsp; {lookup.map((m, ix) => {&nbsp; &nbsp; &nbsp; &nbsp; return <option&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={m.id}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={ix}&nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{m.value}&nbsp; &nbsp; &nbsp; &nbsp; </option>&nbsp; &nbsp; &nbsp; })};&nbsp; &nbsp; </select>&nbsp; &nbsp; {value &&&nbsp; &nbsp; <div style={{marginTop: "2rem"}}>&nbsp; &nbsp; &nbsp; You selected ID <span>{value.id}</span>&nbsp; &nbsp; &nbsp; value&nbsp; &nbsp; &nbsp; <span>{value.value}</span>&nbsp; &nbsp; </div>}&nbsp; &nbsp;</div>;}ReactDOM.render(<List/>, document.querySelector('#mount'));body, select, option {&nbsp;font-size: 20px;}select, option {&nbsp;padding: 0.5rem;}body {&nbsp; padding: 2rem;}span {&nbsp; font-weight: bold;&nbsp; margin: 1em;&nbsp; background-color: yellow;&nbsp; border: 1px solid black;&nbsp; padding: 1em 1.5rem;&nbsp; border-radius: 50%;}<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script><script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="mount"/>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答