const handleChange = (e) => {
console.log(e.target.id);
};
return (
<div>
<select onChange={(e) => handleChange(e)}>
<option value="1-10" id="foo">
1-10
</option>
我怎样才能制作id
<option>
中的 Prop 标签可以通过上面的代码访问吗? e.target.id
不返回任何内容,但 e.target.value
返回选定的值。使用普通 html 元素时如何创建这些自定义属性?
最佳答案
实现此目的的最简单方法之一如下:
const handleChange = (e) => {
const index = e.target.selectedIndex;
const id = e.target.childNodes[index].id;
console.log(id); // logs 'foo' or 'bar' depending on selection
};
return (
<div>
<select onChange={(e) => handleChange(e)}>
<option value="1-10" id="foo">
1-10
</option>
<option value="11-20" id="bar">
11-20
</option>
</select>
</div>
);
关于javascript - React 添加自定义 props 到普通 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71538801/