Javascript 在 React 中使用多个选项从 <select> 检索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28624763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:07:29  来源:igfitidea点击:

Retrieving value from <select> with multiple option in React

javascriptdomreactjs

提问by Inkling

The React way to set which option is selected for a select box, is to set a special valueprop on the <select>itself, corresponding to the valueattribute on the <option>element you desire to be selected. For a multipleselect this prop can accept an array instead. (Edit: Currently the documentation seems to have removed reference to this)

设置选择框选择哪个选项的 React 方法是value在其<select>自身上设置一个特殊的prop ,对应于您希望被选择value<option>元素上的属性。对于multiple选择,这个道具可以接受一个数组。(编辑:目前文档似乎已删除对此的引用)

Now because this is a special attribute, I'm wondering what the canonical way is to retrievethe 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 valueproperty won't be available on the DOM element.

现在因为这是一个特殊的属性,我想知道当用户更改内容时在相同的选项值结构数组中检索所选选项的规范方法是什么(因此我可以通过回调将其传递给父组件等),因为大概相同的value属性在 DOM 元素上不可用。

To use an example, with a text field you would do something like this (JSX):

举个例子,对于一个文本字段,你可以做这样的事情(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>
    );
  }
});

回答by Jonny Buchanan

The same way you do anywhere else, since you're working with the real DOM node as the target of the change event:

与您在其他任何地方所做的相同,因为您使用真实的 DOM 节点作为更改事件的目标:

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);
}

回答by jamesmfriedman

Easiest way...

最简单的方法...

handleChange(evt) {
  this.setState({multiValue: [...evt.target.selectedOptions].map(o => o.value)}); 
}

回答by Mendes

With Array.from()and e.target.selectedOptionsyou can perform a controlled select-multiple:

使用Array.from()e.target.selectedOptions您可以执行受控的多选:

handleChange = (e) => {
  let value = Array.from(e.target.selectedOptions, option => option.value);
  this.setState({values: value});
}

target.selectedOptions return a HTMLCollection

target.selectedOptions 返回一个 HTMLCollection

https://codepen.io/papawa/pen/XExeZY

https://codepen.io/papawa/pen/XExeZY

回答by Max Podriezov

In case you want to use refyou can get selected values like this:

如果您想使用,ref您可以像这样获得选定的值:

var select = React.findDOMNode(this.refs.selectRef); 
var values = [].filter.call(select.options, function (o) {
      return o.selected;
    }).map(function (o) {
      return o.value;
    });

2018 ES6update

2018 ES6更新

  let select = this.refs.selectRef;
  let values = [].filter.call(select.options, o => o.selected).map(o => o.value);

回答by rambossa

In the case you would like to keep track of the selected options while the form is being completed:

如果您想在填写表格时跟踪所选选项:

handleChange(e) {
    // assuming you initialized the default state to hold selected values
    this.setState({
        selected:[].slice.call(e.target.selectedOptions).map(o => {
            return o.value;
        });
    });
}

selectedOptionsis an array-like collection/list of elements related to the DOM. You get access to it in the event target object when selecting option values. Array.prototype.sliceand callallows us to create a copy of it for the new state. You could also access the values this way using a ref (in case you aren't capturing the event), which was another answer for the question.

selectedOptions是与 DOM 相关的类似数组的元素集合/列表。选择选项值时,您可以在事件目标对象中访问它。Array.prototype.slicecall允许我们为新状态创建它的副本。您还可以使用 ref 以这种方式访问​​值(以防您没有捕获事件),这是该问题的另一个答案。

回答by Lanci

You can actually find the selectedOptionsinside the target... no need to iterate over all the options. Let's imagine you want to send the values to an onChangefunction passed to your component as props: you can use the following function on the onChangeof your multiple select.

您实际上可以找到selectedOptions目标的内部……无需遍历所有选项。假设您想将值发送到onChange作为道具传递给组件的函数:您可以在onChange多项选择中使用以下函数。

onSelectChange = (e) => {
    const values = [...e.target.selectedOptions].map(opt => opt.value);
    this.props.onChange(values);
  };

回答by mantish

The following worked for me

以下对我有用

var selectBoxObj = React.findDOMNode(this.refs.selectBox)
var values = $(selectBoxObj).val()

回答by Aral Roca

Another way to do it:

另一种方法:

handleChange({ target }) {
    this.props.someCallback(
       Array.prototype.slice.call(target.selectedOptions).map(o => o.value)
    )
}

回答by Slavi Vatahov

Try this one:

试试这个:

dropdownChanged = (event) => {
    let obj = JSON.parse(event.target.value);
    this.setState(
        {
            key: obj.key,
            selectedName: obj.name,
            type: obj.type
        });
}


<select onChange={this.dropdownChanged} >
<option value={JSON.stringify({ name: 'name', key: 'key', type: "ALL" })} >All Projetcs and Spaces</option></select>