我使用的是React,我希望只使用单击来选择/取消选择多选择中的项,而不是"ctrl + click",在java脚本和jquery中可以使用下面的代码
$('option').mousedown(function(e) {
    e.preventDefault();
    $(this).prop('selected', !$(this).prop('selected'));
    return false;
});有用React实现的方法吗?
我的密码是这样的
import React, { useState } from "react";
import { Col, Form } from "react-bootstrap";
export default function App() {
  const [field, setField] = useState([]);
  return (
    <Form.Group as={Col} controlId="my_multiselect_field">
      <Form.Label>My multiselect</Form.Label>
      <Form.Select multiple aria-label="Default select example" multiple value={field} onChange={e => setField([].slice.call(e.target.selectedOptions).map(item => item.value))}>
        <option value="field1">Field 1</option>
        <option value="field2">Field 2</option>
        <option value="field3">Field 3</option>
      </Form.Select>
    </Form.Group>
  );
}发布于 2022-09-14 10:27:14
通过这样做,我就能做到这一点。我有两种状态,一种是选项,另一种是我选择的所有选项。现在,在handleChange函数中,我正在检查该值是否是新值,将其添加到数组中,否则删除它。
注意:现在无需使用ctrl就可以添加多个项。
import React, { useState } from "react";
export function App(props) {
  const [options, setOptions] = useState(["field1", "field2", "field3"]);
  const [selected, setSelected] = useState([]);
  const handleChange = (e) => {
    e.preventDefault();
    let newArr = [];
    // checking if its exists remove it
    if (selected.includes(e.target.value)) {
      newArr = selected.filter((item) => item != e.target.value);
    } else {
      // eles adding into selected array
      newArr = [...selected, e.target.value];
    }
    // update state
    setSelected(setSelected);
  };
  return (
    <div className="App">
      <select multiple value={selected} onChange={handleChange}>
        {options.map((singleOption, index) => (
          <option key={index} value={singleOption}>
            {singleOption}
          </option>
        ))}
      </select>
    </div>
  );
}https://stackoverflow.com/questions/73714630
复制相似问题