如何实现MUI Autocomplete点击清除图标后始终保留选中选项
解决MUI Autocomplete始终保持至少一个选项选中的问题
要实现点击清除图标或取消最后一个选项时始终保留至少一个选中项,需要将组件改为受控模式,通过拦截值的变更来限制选中数组的最小长度。具体实现如下:
关键修改点
- 用React状态管理选中值,替代非受控的
defaultValue - 在
onChange事件中判断新选中数组的长度,若为空则不更新状态,保留当前选中值 - 同时拦截用户手动取消最后一个选项的操作
修改后的完整代码
import * as React from "react"; import Checkbox from "@mui/material/Checkbox"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank"; import CheckBoxIcon from "@mui/icons-material/CheckBox"; import DeleteIcon from "@mui/icons-material/Delete"; const icon = <CheckBoxOutlineBlankIcon fontSize="small" />; const checkedIcon = <CheckBoxIcon fontSize="small" />; const clearIcon = <DeleteIcon fontSize="small" />; export default function CheckboxesTags() { // 用状态管理选中值,初始化为默认选项 const [selectedFilms, setSelectedFilms] = React.useState([top100Films[0]]); const handleChange = (event, newValue) => { // 仅当新选中数组长度大于0时更新状态 if (newValue.length > 0) { setSelectedFilms(newValue); } }; return ( <Autocomplete multiple open={true} limitTags={1} id="checkboxes-tags-demo" clearIcon={clearIcon} options={top100Films} disableCloseOnSelect // 受控模式绑定value和onChange value={selectedFilms} onChange={handleChange} getOptionLabel={(option) => option.title} renderOption={(props, option, { selected }) => ( <li {...props}> <Checkbox icon={icon} checkedIcon={checkedIcon} style={{ marginRight: 8 }} checked={selected} /> {option.title} </li> )} style={{ width: 500 }} renderInput={(params) => ( <TextField {...params} label="Checkboxes" placeholder="Search Labels" /> )} /> ); } 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 }, { title: "12 Angry Men", year: 1957 }, { title: "Schindler's List", year: 1993 }, { title: "Pulp Fiction", year: 1994 }, ];
说明
- 受控模式下,通过
value绑定状态、onChange控制状态更新,实现对选中值的完全掌控 handleChange函数直接拦截了所有会导致选中数组为空的操作,包括点击清除图标、手动取消最后一个选项- 初始选中逻辑与原需求一致,默认选中第一个选项
内容的提问来源于stack exchange,提问作者Happy1234
相关产品推荐
相关产品推荐

