从< select>中检索值在React中有多个选项 [英] Retrieving value from <select> with multiple option in React
问题描述
为选择框选择哪个选项的React方式是在< select>
The React way to set which option is selected for a select box, is to set a special value
attribute on the <select>
itself, corresponding to the value
attribute on the <option>
element you desire to be selected. For a multiple
select this attribute can accept an array instead. (Edit: Currently the documentation seems to have removed reference to this)
现在因为这是一个特殊的属性,我想知道规范的方法是在用户更改事物(因此我可以将其通过回调传递给父组件等)时,以相同的option-of-option-values-structure结构来检索所选择的选项,因为可能相同的值
属性将不会在DOM元素上可用。
Now because this is a special attribute, I'm wondering what the canonical way is to retrieve the selected options in the same array-of-option-values-structure when the user changes things (so I can pass it through a callback to a parent component etc), since presumably the same value
property won't be available on the DOM element.
要使用示例,使用文本字段你会做这样的事情(JSX):
To use an example, with a text field you would do something like this (JSX):
var TextComponent = React.createClass({
handleChange: function(e) {
var newText = e.target.value;
this.props.someCallbackFromParent(newText);
},
render: function() {
return <input type="text" value={this.props.someText} onChange={this.handleChange} />;
}
});
相当于替换 ???
这个多选择组件?
What is the equivalent to replace ???
for this multiple select component?
var MultiSelectComponent = React.createClass({
handleChange: function(e) {
var newArrayOfSelectedOptionValues = ???;
this.props.someCallbackFromParent(newArrayOfSelectedOptionValues);
},
render: function() {
return (
<select multiple={true} value={this.props.arrayOfOptionValues} onChange={this.handleChange}>
<option value={1}>First option</option>
<option value={2}>Second option</option>
<option value={3}>Third option</option>
</select>
);
}
});
推荐答案
与其他任何地方一样,重新使用真正的DOM节点作为更改事件的目标:
The same way you do anywhere else, since you're working with the real DOM node as the target of the change event:
handleChange: function(e) {
var options = e.target.options;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
this.props.someCallback(value);
}
这篇关于从< select>中检索值在React中有多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!