【问题标题】:Multiselect in React Component - how to set state with all selected values?React Component中的多选 - 如何使用所有选定值设置状态?
【发布时间】:2020-07-14 09:49:46
【问题描述】:

我在将所有选定值添加到状态(挂钩)时遇到问题。这是我的代码示例:

   <div className="row">
        <div className="input-field col s12">
          <select multiple onChange={props.handleSelectedMultiple} id="balcony">
            <option value="" disabled>
              Brak
            </option>
            <option value="Balkon">Balkon</option>
            <option value="Taras">Taras</option>
            <option value="Ogród">Ogród</option>
            <option value="Loggia">Loggia</option>
            <option value="Taras na dachu">Taras na dachu</option>
          </select>
          <label>Balkon</label>
        </div>
      </div>

和功能:

 const handleSelectedMultiple = e => {
    console.log(e.target.value);
  };

问题是console.log 中的值来自FIRST SELECTED OPTION,所以当我在控制台中按Taras、Ogród、Loggia 的顺序选择时,我有(3)Taras。目标是添加以声明所有选定的值。

有人吗?

【问题讨论】:

  • 它对我来说很好用,我可以像这样正确获取值
  • Taras test.js:4 Ogród test.js:4 Loggia test.js:4 Taras na dachu test.js:4 Taras test.js:4 Balkon

标签: reactjs forms select multi-select


【解决方案1】:

您需要计算所选选项。你可以做类似的事情

const handleSelectedMultiple = evt => {
    const values = Array.from(evt.target.selectedOptions, option => option.value);
    // Or this way
   // const values = [...evt.target.selectedOptions].map(opt => opt.value)
    console.log('values', values);
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2023-02-16
    • 2022-12-25
    • 2020-07-21
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多