【问题标题】:How to get selected option in React.js not jQuery or any other framework?如何在 React.js 而不是 jQuery 或任何其他框架中获得选定的选项?
【发布时间】:2020-08-11 01:34:59
【问题描述】:

我使用了页面 (get selected option id) 中提到的方式,但在 React.js 中我以这种方式挣扎,但 this 未定义。如何获取所选选项的 id?

<select id="my_select" onchange={() => handleChange(this)}>
   <option value="o1" id="id1">Option1</option>
   <option value="o2" id="id2">Option2</option>
</select>

这是我的onChange() 函数:

const handleChange = (obj) => {
    console.log("What is this?", obj); // --> undefined

};

如何获取所选选项的 id?

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    首先,请记住您可以将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 函数(并且还为onChangehandleChange 声明了箭头函数)它将为我们提供实际的@ 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] 访问第一个项目,并通过点符号获得您想要的属性。

    thisevent 的工作示例:

    【讨论】:

    • 我想获取所选选项的 id 而不是选择标签的值。
    • @s.hesam 检查这个developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/…(所以event.target.selectedOptions[0].id
    • @s.hesam 正如@arieljuod 所说,您可以通过访问提供所选选项元素的event.target.selectedOptions 来简单地做到这一点。
    猜你喜欢
    • 2017-03-16
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多