我做了一个可滚动列表。我选择的列表中的每一个项目都将上升为芯片(灰色的)。但是当我再次点击列表上的同一项时,它就会不断地增加筹码。我想删除选定的,所以没有重复的芯片。(删除芯片功能已工作)
我该怎么做?
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
1条答案
按热度按时间yshpjwxd1#
您可能希望通过检查
dataFiltered
中的选定项是否位于selected
数组中来删除这些项。例如:或