[英]What is the proper way to get the value of a React <select> element?
Say I have the following React element ( example fiddle here ): 假设我有以下React元素( 此处是示例小提琴 ):
var Hello = React.createClass({
getInitialState: function() {
return {parsed: false};
},
_parseEvent: function(event) {
var parser1 = event.currentTarget.selectedOptions[0].value;
var parser2 = event.target.value;
var parser3 = event.nativeEvent.srcElement.value;
if (parser1 && parser2 && parser3)
this.setState({parsed: true});
},
render: function() {
var parsing = "parsing worked";
return (
<div>
<select
onChange={this._parseEvent}>
<option value="----">----</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<p>
{ this.state.parsed ?
{parsing}
: null}
</p>
</div>
);
}
});
React.render(<Hello name="World" />, document.getElementById('container'));
I'm using three ways of parsing the value of the <select>
element. 我正在使用三种方法来解析
<select>
元素的值。 The first does not work on IE 10, and I know it's a bug per my question here . 第一个在IE 10上不起作用,我知道这是每个问题的错误。 However, of the other two ways,
parser2
or parser3
, which is the proper way to get the value of a <select>
element in React? 但是,在其他两种方法中,
parser2
或parser3
,这是在React中获取<select>
元素值的正确方法吗? Why? 为什么? Thanks for any help!
谢谢你的帮助!
Use what you would use in a W3C compatible browser: 使用在W3C兼容浏览器中将使用的内容:
event.target.value
This is also agnostic to the type of the form control element. 这也与表单控制元素的类型无关。
While the other answer works just fine, if you're looking for a React way, then this can be accomplished by using refs. 虽然其他答案很好用,但是如果您正在寻找一种React方法,那么可以通过使用refs来完成。
Assign a ref to the select: 给选择分配一个参考:
<select onChange={this._parseEvent} ref="select">
<option value="----">----</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
/select>
Get the DOM node via ref: 通过ref获取DOM节点:
var node = React.findDOMNode(this.refs.select)
Get the value via DOM node: 通过DOM节点获取值:
var value = node.value;
Here's an updated fiddle to demonstrate: https://jsfiddle.net/ve88383c/4/ 这是演示的更新小提琴: https : //jsfiddle.net/ve88383c/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.