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

Bom*_*ber 24 javascript reactjs

我有我的选择列表组件呈现我的选择列表:

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

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

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

},
Run Code Online (Sandbox Code Playgroud)

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

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

有没有办法可以获得选项文本?这给了我不确定的

event.nativeEvent.target.text; //undefined
Run Code Online (Sandbox Code Playgroud)

Dhi*_*raj 52

这样的事应该做

var index = event.nativeEvent.target.selectedIndex;
event.nativeEvent.target[index].text
Run Code Online (Sandbox Code Playgroud)

这是一个演示http://jsbin.com/vumune/4/

  • 上帝祝福你!! (6认同)

Sea*_*lls 25

您可以通过替换此选项来获取选项文本:

event.nativeEvent.target.text;
Run Code Online (Sandbox Code Playgroud)

有了这个:

event.target.options[event.target.selectedIndex].text
Run Code Online (Sandbox Code Playgroud)


Olb*_*bor 7

这对我有用

const {options, value} = e.target;
console.log(options[value].innerHTML);
Run Code Online (Sandbox Code Playgroud)

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

const {options, selectedIndex} = e.target;
console.log(options[selectedIndex].innerHTML);
Run Code Online (Sandbox Code Playgroud)


小智 6

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

e.target.selectedOptions[0].text