从 <select> 中检索值在 React 中有多个选项 [英] Retrieving value from <select> with multiple option in React
问题描述
React 设置选择框选择哪个选项的方法,是在 本身上设置一个特殊的
value
属性,对应于 <您希望被选中的 元素上的 code>value 属性.对于
multiple
选择这个 prop 可以接受一个数组.
The React way to set which option is selected for a select box, is to set a special value
prop on the <select>
itself, corresponding to the value
attribute on the <option>
element you desire to be selected. For a multiple
select this prop can accept an array instead.
现在因为这是一个特殊的属性,我想知道当用户更改内容时检索相同数组选项值结构中的选定选项的规范方法是什么(所以我可以通过回调将它传递给父组件等),因为大概相同的 value
属性在 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>
);
}
});
推荐答案
使用 Array.from()
和 e.target.selectedOptions
您可以执行受控选择-多个:
With Array.from()
and e.target.selectedOptions
you can perform a controlled select-multiple:
handleChange = (e) => {
let value = Array.from(e.target.selectedOptions, option => option.value);
this.setState({values: value});
}
target.selectedOptions 返回一个 HTMLCollection
target.selectedOptions return a HTMLCollection
https://codepen.io/papawa/pen/XExeZY
这篇关于从 <select> 中检索值在 React 中有多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!