使用 React js 获取选定的选项文本?

Get selected option text using react js?

我有 select 列表组件呈现我的 select 列表:

<form className="pure-form">
<select ref="selectMark" className="mark-selector"
 onChange={this.onChange}>{this.getOptions()}
</select>
</form>

我在组件上有一个创建选项的方法:

getOptions: function () {
    return this.props.renderProps.data.map(function (item) {
        return <option key={item.value} value={item.value}>{item.label}</option>;
    }.bind(this));

},

我的 onChange 方法适用于以下值:

onChange: function(event) {
    var newValue = event.nativeEvent.target.value;
    this.props.renderProps.onSaveCare(newValue);
    this.setState({value: newValue});
    this.toggleEdit();
},

有什么方法可以获得选项文本吗?这给了我 undefined

event.nativeEvent.target.text; //undefined

应该这样做

var index = event.nativeEvent.target.selectedIndex;
event.nativeEvent.target[index].text

这里有演示http://jsbin.com/vumune/4/

选项的文本只是相应itemlabel 属性。

在您的情况下,要检索所选选项的文本,您可以执行以下操作:

var selectedItem = this.props.renderProps.data.find(function (item) {
  return item.value === event.target.value;
});
selectedItem.label;

Array.prototype.find is part of the ES6 proposal. Underscore or lodash already package it as the _.find method.

如果是单人select,这里有更简单的方法:

e.target.selectedOptions[0].text

您可以通过替换以下内容来获取选项文本:

event.nativeEvent.target.text;

有了这个:

event.target.options[event.target.selectedIndex].text

这对我有用

const {options, value} = e.target;
console.log(options[value].innerHTML);

编辑:我刚刚意识到我正在使用 "value" 字段来存储一些对象的 ID,从 0 到 n。我想更好的方法可能是:

const {options, selectedIndex} = e.target;
console.log(options[selectedIndex].innerHTML);

Here what i do to retrieve the text from select option in react js.

this.refs.selectMark[this.refs.selectMark.value].text

2020 年,这对我有用

我的 Select 元素:

          <FormGroup>
                  {<Select
                    closeMenuOnSelect={true}
                    components={animatedComponents}
                    options={Options}
                    value = "Ahmedabad"
                    onChange={this.handleChange}
                    name = "citySelect"
                  />}
          </FormGroup>

呼叫处理程序:

handleChange = (e) => {
    console.log(e.value)
}

相应地更改您的菜单项

当前/临时地址 永久地址 办公/营业地址

并在更改事件中获得

onChange = {(e,index)  =>
( setAddressChangeType(e.target.value),  console.log(index.props.id) )
} 

相应地制作您的下拉菜单并获得像

这样的更改事件的价值
onChange = {(e,index)  =>
( setAddressChangeType(e.target.value),  console.log(index.props.id) )
}  

使用 refs 很容易。

导入钩子

import React, { useContext, useState, useEffect, useRef } from "react";

实例化它

const yourNewRef= useRef();

在你的元素中引用它

ref={yourNewRef}

然后你可以在任何事件或函数中访问它,只需调用:

let textSelectOption = yourNewRef.current.options[yourNewRef.current.selectedIndex].text

您只需调用

即可访问该值
let optionValue = yourNewRef.current.value

refs 很棒,您几乎可以使用 jQuery 做任何事情。 查看控制台上的 yourNewRef 并通过 .current 属性

访问所有内容