Retrieving value from <select> with multiple option in React

前端 未结 9 1318
无人共我
无人共我 2020-12-02 08:21

The React way to set which option is selected for a select box, is to set a special value prop on the

提交评论

  • 2020-12-02 09:24

    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 return a HTMLCollection

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

    0 讨论(0)
  • 2020-12-02 09:25

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

    onSelectChange = (e) => {
        const values = [...e.target.selectedOptions].map(opt => opt.value);
        this.props.onChange(values);
      };
    
    0 讨论(0)
  • 提交回复
    热议问题