如何在ReactJS和Material UI的多选Chip组件中设置默认值
在Material UI多选Chip组件中设置默认值的解决方案
要给这个多选Chip组件设置默认选中值,只需修改状态的初始值即可,具体实现如下:
核心修改点
组件的选中状态由personName状态变量控制,直接在useState中传入包含默认选中项的数组即可,注意数组中的值必须和names数组里的选项完全一致。
修改后的完整代码
import * as React from 'react'; import { useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import OutlinedInput from '@mui/material/OutlinedInput'; import InputLabel from '@mui/material/InputLabel'; import MenuItem from '@mui/material/MenuItem'; import FormControl from '@mui/material/FormControl'; import Select from '@mui/material/Select'; import Chip from '@mui/material/Chip'; const ITEM_HEIGHT = 48; const ITEM_PADDING_TOP = 8; const MenuProps = { PaperProps: { style: { maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP, width: 250, }, }, }; const names = [ 'Oliver Hansen', 'Van Henry', 'April Tucker', ]; function getStyles(name, personName, theme) { return { fontWeight: personName.indexOf(name) === -1 ? theme.typography.fontWeightRegular : theme.typography.fontWeightMedium, }; } export default function MultipleSelectChip() { const theme = useTheme(); // 设置默认选中Van Henry和April Tucker const [personName, setPersonName] = React.useState(['Van Henry', 'April Tucker']); const handleChange = (event) => { const { target: { value }, } = event; setPersonName( // 处理自动填充时的字符串值 typeof value === 'string' ? value.split(',') : value, ); }; return ( <div> <FormControl sx={{ m: 1, width: 300 }}> <InputLabel id="demo-multiple-chip-label">Chip</InputLabel> <Select labelId="demo-multiple-chip-label" id="demo-multiple-chip" multiple value={personName} onChange={handleChange} input={<OutlinedInput id="select-multiple-chip" label="Chip" />} renderValue={(selected) => ( <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}> {selected.map((value) => ( <Chip key={value} label={value} /> ))} </Box> )} MenuProps={MenuProps} > {names.map((name) => ( <MenuItem key={name} value={name} style={getStyles(name, personName, theme)} > {name} </MenuItem> ))} </Select> </FormControl> </div> ); }
注意事项
- 默认值数组中的每一项必须与
MenuItem的value属性完全匹配,否则组件无法识别并渲染选中状态。 - 组件会自动根据初始状态渲染对应的Chip,同时
getStyles函数会给已选中的选项设置加粗样式,保持UI一致性。
内容的提问来源于stack exchange,提问作者denise
相关产品推荐
相关产品推荐

