javascript - 如何在下拉切换中获取多个选定的列表项 values?

需要在不删除以前加载的 value 的情况下在下拉切换中获取所有选定的 values,请帮助

const [selectedItem, setSelectedItem] = useState("Select...");
<Dropdown className="dropdown-groove">
        <Dropdown.Toggle variant="outline-secondary " id="dropdown-basic">
          {selectedItem}
          <label className="dropdown-label">Dropdown label</label>
        </Dropdown.Toggle>

        <Dropdown.Menu>
          <Dropdown.Item href="#/action-1">
            {" "}
            <Form.Check
              onClick={(e) => {
                setSelectedItem("List A");
                e.stopPropagation();
              }}
              className="checkbox-groove"
              inline
              label="List Item 1"
              name="group1"
              type="checkbox"
            />{" "}
          </Dropdown.Item>
          <Dropdown.Item href="#/action-2">
            {" "}
            <Form.Check
              onClick={(e) => {
                setSelectedItem("List b");
                e.stopPropagation();
              }}
              className="checkbox-groove"
              inline
              label="List Item 2"
              name="group1"
              type="checkbox"
            />{" "}
          </Dropdown.Item>
</Dropdown.Menu>
</Dropdown>

https://codesandbox.io/s/dropdown-with-checkboxs-nvw3hz

回答1

您可以在第 6 行的 setState 之后声明一个函数

function toggleCheckbox(addItem) {
    if (selectedItem.indexOf(addItem) < 0) {
      setSelectedItem(`${selectedItem} ${addItem}`);
    } else {
      setSelectedItem(selectedItem.replace(addItem, ""));
    }
  }

并将 setSelectedItem("List A"); 替换为 toggleCheckbox("List A"); 然后, List b & c 是相同的替换方法。

https://codesandbox.io/s/dropdown-with-checkboxs-forked-ov7mk2?file=/src/App.js