You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React的Material UI多选选择器中设置默认值?

为Material UI多选选择器设置默认选中值

我需要为React项目中的Material UI多选选择器设置默认选中值,其中valueSheet.userFullName是存储所有用户信息的数组,恳请大家帮忙指导实现方法。我的组件代码如下:

export default function MultipleSelectBox() {
  const valueSheet = useContext(ContextSheet);

  const [personName, setPersonName] = React.useState([]);

  const handleChange = (event, key) => {
    const itemKey = key.key.slice(2);
    console.log("keyyy", itemKey);
    valueSheet.setUserUid(current => [...current, itemKey]);
    const { target: { value } } = event;
    setPersonName(
      typeof value === 'string' ? value.split(',') : value,
    );
    console.log("getSelectedValue", event.target.value);
  };

  return (
    <div>
      <InputLabel id="demo-simple-select-standard-label">Users List :</InputLabel>
      <FormControl sx={{ m: 1, width: 210 }} size="small">
        <InputLabel id="demo-multiple-checkbox-label">Users</InputLabel>
        <Select
          labelId="demo-multiple-checkbox-label"
          id="demo-multiple-checkbox"
          multiple
          value={personName}
          onChange={handleChange}
          input={<OutlinedInput label="Users" />}
          renderValue={(selected) => {
            console.log("selectedd", selected);
            return selected.map((s) => s.FullName).join(", ");
          }}
          MenuProps={MenuProps}
        >

          {valueSheet.userFullName.map((name) => {
            return (
              <MenuItem key={name.id} value={name}>
                <Checkbox checked={personName.indexOf(name) > -1} />
                <ListItemText primary={name.FullName} />
              </MenuItem>
            );
          })}
        </Select>
      </FormControl>
    </div>
  );
}

实现方法

1. 初始化默认选中状态

默认选中值的核心是把personName的初始状态设置为你需要预先选中的用户数组,分两种场景处理:

  • 固定默认项:如果明确知道要选中的用户(比如id为1、3的用户),直接在useState中过滤:
    const [personName, setPersonName] = React.useState(
      valueSheet.userFullName.filter(user => [1, 3].includes(user.id))
    );
    
  • 异步默认项:如果默认选中的用户id来自上下文或接口(比如valueSheet.defaultSelectedUids),用useEffect监听数据变化后更新状态:
    React.useEffect(() => {
      if (valueSheet.userFullName.length) {
        const defaultSelected = valueSheet.userFullName.filter(user => 
          valueSheet.defaultSelectedUids.includes(user.id)
        );
        setPersonName(defaultSelected);
      }
    }, [valueSheet.userFullName, valueSheet.defaultSelectedUids]);
    

2. 修复选中判断逻辑

用户对象是引用类型,原代码中personName.indexOf(name) > -1可能因引用不一致导致判断失效,改用id匹配更可靠:

<Checkbox checked={personName.some(item => item.id === name.id)} />

3. 优化选中事件处理

原代码中key参数处理多余,且setUserUid的追加逻辑不符合多选的选中/取消逻辑,改成同步选中的id列表:

const handleChange = (event) => {
  const { target: { value } } = event;
  const selectedUsers = typeof value === 'string' ? value.split(',') : value;
  setPersonName(selectedUsers);
  // 同步选中的用户id到上下文
  valueSheet.setUserUid(selectedUsers.map(user => user.id));
};

内容的提问来源于stack exchange,提问作者Humail Saleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:20:33