0

我有一个下拉菜单。用户可以从下拉列表中选择多个项目。同时,用户可以通过再次单击选中的项目来取消选择他们已经选择的项目。如果用户选择全部,将显示数组中的所有数字。

如何实施?这就是我到目前为止在此处输入链接描述的内容

import "./styles.css";
import React, { useState } from "react";

const options = [1, 2, 3, 4, 5];

export default function App() {
  const [nums, setNum] = useState([]);

  const handleArrChange = ({ target }) => {
    setNum([...nums, target.value]);
  };
  return (
    <div className="App">
      <select
        onChange={handleArrChange}
        value={"select a number" || nums.length > 0}
      >
        <option disabled>select a number</option>
        {options.map((option) => (
          <option>{option}</option>
        ))}
      </select>
      {nums.map((num) => (
        <p>{num}</p>
      ))}
    </div>
  );
}
4

2 回答 2

0

现场工作示例:https ://react-3gte8y.stackblitz.io/

代码:https ://stackblitz.com/edit/react-3gte8y?file=src/App.js

首先让您的选项数组只包含数字:

const options = [1, 2, 3, 4, 5];

然后在您的 onChange 处理程序函数中检查所选值是否已经存在于 nums 状态,如果不存在则添加它,否则将其删除怎么办?使用方法轻松获取值的索引indexOf,如果返回 -1 表示num数组中不存在数字,否则 indexOf 将返回您选择的数字的实际索引:

const handleArrChange = ({ target }) => {

        setNum((prev) => {

          //get index of actual target.value
          const index = prev.indexOf(target.value);

          /*if index === -1 means not exist in array will return the prev 
          state and appending new chosen value*/
          if (index === -1) {

            return [...prev, target.value];

          }

           /* else (value exist) use splice to remove the chosen value from 
           the array */
          prev.splice(index, 1);

          /* don't use return prev, React will not detect changes in your 
          state and will not re render it */
          return [...prev];

        });
      };

prev 是前一个状态,它在对 num 状态进行任何更改之前保持实际状态。

现在对您的 JSX 进行一些更改,首先不要忘记键,并确保将默认选择值设置select为禁用选项:

<select onChange={handleArrChange} value={"select"}>
    <option disabled>select</option>
    {options.map((option) => (
        <option key={option}>{option}</option>
    ))}
</select>

{nums.map((num) => (
        <p key={num}>{num}</p>
      ))}

现在您需要做的一件事是全选并取消全选

首先将所有选项添加到您的选项中:

<select onChange={handleArrChange} value={"select"}>
        <option disabled>select</option>
        <option>All</option>
        {options.map((option) => (
          <option key={option}>{option}</option>
        ))}
</select>

然后在 onChange 函数处理程序中检查是否是 All 被检查:

if(target.value === "All"){
        if(nums.length > 0 ){
            setNum([])
        }else{
            setNum(options)
        }
        return
    }

此代码必须是您在选择值更改时首先执行的操作,将其添加到 onChange 函数的顶部:

这是完整的工作代码:

import React, { useState } from "react";

const options = [1, 2, 3, 4, 5];

export default function App() {


  const [nums, setNum] = useState([]);
  
  const handleArrChange = ({ target }) => {

    if(target.value === "All"){
        if(nums.length > 0 ){
            setNum([])
        }else{
            setNum(options)
        }
        return
    }

    setNum((prev) => {

      const index = prev.indexOf(target.value);

      if (index === -1) {

        return [...prev, target.value];

      }

      prev.splice(index, 1);

      

      return [...prev];
    });

  };
  return (
    <div className="App">

        <select onChange={handleArrChange} value={"select"}>

            <option disabled>select</option>

            <option>All</option>

            {options.map((option) => (

            <option key={option}>{option}</option>

            ))}

        </select>

        {nums.map((num) => (

            <p key={num}>{num}</p>

        ))}

    </div>

  );
}
于 2021-05-30T01:10:42.727 回答
0

看起来像一个多重选择器(选择的自定义实现)

例子:

import React, { useState } from 'react';
import Select from 'react-select';
 
function App() {
  const data = [
    {
      value: 1,
      label: "cerulean"
    },
    {
      value: 2,
      label: "fuchsia rose"
    },
    {
      value: 3,
      label: "true red"
    },
    {
      value: 4,
      label: "aqua sky"
    },
    {
      value: 5,
      label: "tigerlily"
    },
    {
      value: 6,
      label: "blue turquoise"
    }
  ];
 
  // set value for default selection
  const [selectedValue, setSelectedValue] = useState([]);
 
  // handle onChange event of the dropdown
  const handleChange = (e) => {
    setSelectedValue(Array.isArray(e) ? e.map(x => x.value) : []);
  }
 
  return (
    <div className="App">
      <h3>Get selected by only value for multi select - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
 
      <Select
        className="dropdown"
        placeholder="Select Option"
        value={data.filter(obj => selectedValue.includes(obj.value))} // set selected values
        options={data} // set list of the data
        onChange={handleChange} // assign onChange function
        isMulti
        isClearable
      />
 
      {selectedValue && <div style={{ marginTop: 20, lineHeight: '25px' }}>
        <div><b>Selected Value: </b> {JSON.stringify(selectedValue, null, 2)}</div>
      </div>}
    </div>
  );
}
 
export default App;

在此处输入图像描述

参考:https ://www.cluemediator.com/how-to-get-selected-by-only-value-for-multi-select-in-react-select

于 2021-05-29T23:05:39.407 回答