javascript 如何从我的列表中删除选中的项目并将其移动到筹码中,然后当我删除筹码时,它会回到列表中?

6za6bjd0  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(112)

我做了一个可滚动列表。我选择的列表中的每一个项目都将上升为芯片(灰色的)。但是当我再次点击列表上的同一项时,它就会不断地增加筹码。我想删除选定的,所以没有重复的芯片。(删除芯片功能已工作)
我该怎么做?

import React, {useState, useEffect} from 'react'
import {Typography, Paper, Box} from '@mui/material'
import Chip from '@mui/material/Chip';
import SearchInput from '../components/SearchInput';
import DeletableChip from '../components/DeletableChip'
import { spiritualPractice } from '../constants';

const Page9 = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [selected, setSelected] = useState<string[]>([])
  const [newSpiritualPractice, setNewSpiritualPractice] = useState<string[]>([])
  const onDelete = (item) => () => {
    setSelected((value) => value.filter((v) => v !== item));
  };

  const selectPractice = (item) =>{
    setSelected([...selected, item])
  }

  useEffect(() => {
    setSearchQuery("");
  }, [selected])
  

  const filterData = (query, data) => {
    if (!query) {
      return data;
    } else {
      return data.filter((d) => d.toLowerCase().includes(query));
    }
  };

  const dataFiltered = filterData(searchQuery, spiritualPractice);
  
  return (
    <div>
            <Typography variant="h6" mt={2} sx={{ fontWeight: 'bold' }}>Passions</Typography>
            <Typography variant="body2" my={2} sx={{ fontWeight: 'normal' }}>Let everyone know what you're passionate about, by adding it to your profile.</Typography>
            <DeletableChip ></DeletableChip>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', width: 'auto'}}>
              {selected.map((el) => (
                <Chip key={el} label={el} onDelete={onDelete(el)} sx={{m:1}}/>
              ))}
            </Box>
            <SearchInput searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
            <Paper style={{maxHeight: 200, overflowY: 'auto'}}>
              {dataFiltered.map((d) => (
                <div
                  className="text"
                  style={{
                    padding: 5,
                    justifyContent: "normal",
                    fontSize: 13,
                    margin: 1,
                    width: "250px",
                    borderWidth: "10px",
                    overflowY:'auto'
                  }}
                  key={d}
                  onClick={()=> selectPractice(d)}
                >
                  {d}
                </div>
              ))}
            </Paper>
    </div>
  )
}

export default Page9
yshpjwxd

yshpjwxd1#

您可能希望通过检查dataFiltered中的选定项是否位于selected数组中来删除这些项。例如:

const dataFiltered = filterData(searchQuery, spiritualPractice)
  .filter(item => !selected.includes(item));

const filterData = (query, data) => {
  const result = query
    ? data.filter((d) => d.toLowerCase().includes(query))
    : data;
  return result.filter(item => !selected.includes(item));
};

相关问题