[英]MUI Autocomplete remove option after selection
我有一个 Material-UI Autocomplete
组件。 为了防止用户两次选择相同的元素(它会加倍 ID 号),我希望从下拉列表中完全删除该元素。
例如,如果选择了“Shawshank Redemption”,它应该被添加到列表中并从下拉列表中完全删除,但不会更改 JSON 数据。
我试过在filterOptions
上使用过滤器,但这似乎不起作用。
import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import HighlightOffIcon from "@material-ui/icons/HighlightOff";
import IconButton from "@material-ui/core/IconButton";
export default function Playground() {
const defaultProps = {
options: top100Films,
getOptionLabel: (option) => option.title,
filterOptions: (options, state) => {
let newOptions = [];
options.forEach((option) => {
if (option.title.includes(state.inputValue)) {
newOptions.push(option);
}
});
return newOptions.filter((movie) => !movies.includes(movie));
}
};
const [movies, setMovies] = useState([]);
const [key, setKey] = useState(0);
return (
<div style={{ width: 300 }}>
<Autocomplete
{...defaultProps}
id="select-on-focus"
renderInput={(params) => (
<TextField {...params} label="movies" margin="normal" />
)}
onChange={(e, movie) => {
if (movie) {
// this line prevents an error if no movie is selected
setMovies([...movies, movie.title]);
}
// this setKey is supposed to clear the Autocomplete component by forcing a rerender.
// Works in my project but not here.
setKey(key + 1);
}}
/>
<List>
{movies.map((movie) => (
<ListItem key={movie.title}>
<ListItemText primary={movie} />
<IconButton
key={key}
aria-label="delete"
onClick={() => {
setMovies(() => movies.filter((m) => m !== movie));
}}
>
<HighlightOffIcon />
</IconButton>
</ListItem>
))}
</List>
</div>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: "The Shawshank Redemption", year: 1994 },
{ title: "The Godfather", year: 1972 },
{ title: "The Godfather: Part II", year: 1974 },
{ title: "The Dark Knight", year: 2008 },
];
另见: https://codesandbox.io/s/autocomplete-remove-from-list-5dvhg?file=/demo.js:0-6677
编辑:我的项目刚刚更新到 MUI5,所以我正在努力恢复全部功能,然后我会解决这个问题。
将Autocomplete
mode 设置为multiple
并打开filterSelectedOptions
以删除下拉列表中的选定选项。 要在Autocomplete
输入之外正确显示所选选项的列表,请参阅其他答案。
const [movies, setMovies] = useState([]);
<Autocomplete
{...defaultProps}
multiple
filterSelectedOptions
renderTags={() => null} // don't render tag in the TextField
value={movies}
onChange={(e, newValue) => setMovies(newValue)}
/>
为了防止用户两次选择相同的元素(它会加倍 ID 号),我希望从下拉列表中完全删除该元素。
如何禁用它们以便不能再次选择它们?
您可以像getOptionsDisabled
一样传递getOptionLabel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.