2 回答
TA贡献2041条经验 获得超4个赞
您可以将onChange事件处理程序添加到 select 以检查所选索引并从所选选项中检索 id。
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>
TA贡献1874条经验 获得超12个赞
理想情况下,您应该尽量避免从 DOM 获取状态。
如果你控制状态,让 React 来渲染你的状态,React 工作得很好。
下面是一个简单的例子,基本上我所做的就是将状态索引存储到一个数组中。当我更新它时,React 视图将相应地更新。你如何存储状态完全取决于你,而不是 DOM。
const {useState} = React;
const lookup = [
{id: 1, value: 'one'},
{id: 2, value: 'two'},
{id: 3, value: 'three'}
];
function List() {
const [selected, setSelected] = useState(-1);
const value = selected !== -1 && lookup[selected];
return <div>
<select
onChange={(e) => setSelected(e.target.value)}
value={selected}>
<option>Please Selected an option</option>
{lookup.map((m, ix) => {
return <option
key={m.id}
value={ix}
>
{m.value}
</option>
})};
</select>
{value &&
<div style={{marginTop: "2rem"}}>
You selected ID <span>{value.id}</span>
value
<span>{value.value}</span>
</div>}
</div>;
}
ReactDOM.render(<List/>, document.querySelector('#mount'));
body, select, option {
font-size: 20px;
}
select, option {
padding: 0.5rem;
}
body {
padding: 2rem;
}
span {
font-weight: bold;
margin: 1em;
background-color: yellow;
border: 1px solid black;
padding: 1em 1.5rem;
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"/>
添加回答
举报