1. ホーム
  2. javascript

[解決済み] Retrieving value from <select> with multiple option in React

2023-01-13 01:18:17

Question

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.

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)。

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

を置き換えるのと同等なものは何ですか? ??? に相当するものは何でしょうか?

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 であれば、制御されたselect-multipleを実行することができる。

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

target.selectedOptionsはHTMLCollectionを返します。

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