首先,请记住您可以将this 关键字作为参数传递给您的函数。像这样(您提供的代码中还有一个错字,其中onchage 应该是onChange,因为您在这里使用反应元素):
<select id="my_select" onChange={() => handleChange(this)}>
...
</select>
但您不能在实际函数中使用 this 关键字作为输入参数。
const handleChange = (this) => { // This will throw an error (Binding invalid left-hand side ...)
...
};
所以你应该在你的实际函数中使用提供的this关键字访问,就像这样:
const handleChange = (param) => {
console.log("What is this?", param); // Represent the window element
};
这会给我们选择选项值吗?
简短的回答是否,但为什么呢?
由于我们在全局范围内定义了handleChange 函数(并且还为onChange 和handleChange 声明了箭头函数)它将为我们提供实际的@ 987654336@ 元素,对于获取select 值没有用处。
那么最好的方法是什么?
要获取所选选项的实际值,您只需使用event 接口即可,如下所示:
<select id="my_select" onChange={(event) => handleChange(event)}>
...
</select>
const handleChange = (event) => {
console.log("What is this?", event.target.value); // Represent the actual value of selected option
};
注意:您可以阅读有关event 接口here 的更多信息。
更新
当您想访问选定的选项 id 时,您可以通过使用 event.target.selectedOptions 属性来实现,该属性提供了整个选定选项元素的列表,如下所示:
const handleChange = (event) => {
console.log("What is this?", event.target.selectedOptions[0].id); // Represent the actual id of selected option
};
注意:由于event.target.selectedOptions 将提供一组项目,因此您应该使用event.target.selectedOptions[0] 访问第一个项目,并通过点符号获得您想要的属性。
this 和 event 的工作示例: