此代码有效:
import React, { useReducer } from "react";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CheckBoxOutlineBlankIcon from "@material-ui/icons/CheckBoxOutlineBlank";
import CheckBoxIcon from "@material-ui/icons/CheckBox";
import { Chip } from "@material-ui/core";
const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;
const options = [
...
];
const initialState = { selectedOptions: [] };
function reducer(state, action) {
switch (action.type) {
case "SET_SELECTED_OPTIONS":
return { selectedOptions: action.payload.options };
case "REMOVE_OPTION":
return {
selectedOptions: state.selectedOptions.filter(
(option) => option.id !== action.payload.id
)
};
default:
throw new Error();
}
}
export default function App() {
const [state, dispatch] = useReducer(reducer, initialState);
const handleChange = (event, values) => {
dispatch({ type: "SET_SELECTED_OPTIONS", payload: { options: values } });
};
const removeOption = (id) => {
dispatch({ type: "REMOVE_OPTION", payload: { id: id } });
};
return (
<>
<Autocomplete
multiple
options={options}
disableCloseOnSelect
getOptionLabel={(option) => option.title}
value={state.selectedOptions}
renderTags={(values) =>
values.map((value) => (
<Chip
key={value.id}
label={value.title}
onDelete={() => {
removeOption(value.id);
}}
/>
))
}
getOptionSelected={(option, value) => option.id === value.id}
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.title}
</React.Fragment>
)}
style={{ width: 500 }}
onChange={handleChange}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Checkboxes"
placeholder="Favorites"
/>
)}
/>
<Button
variant="contained"
color="secondary"
onClick={() =>
dispatch({
type: "SET_SELECTED_OPTIONS",
payload: {
options: [
{
id: 30,
title: "Once Upon a Time in the West",
year: 1968,
checked: false
}
]
}
})
}
>
Simulate changes from outside
</Button>
<pre>{JSON.stringify(state, null, 2)}</pre>
</>
);
}
如您所见,我使用 react useReducer 函数模拟了您的 redux 存储。您只需存储选定的对象,当它们被删除时,您也只需将它们删除。为此,您必须渲染标签才能访问 onDelete 函数。现在您可以从外部控制所选项目。
现场演示
