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

如何在Material-UI的Autocomplete组件中显示选中选项总数?

在Material-UI Autocomplete组件中显示选中选项总数

需求:点击「Open menu dropdown」按钮打开Autocomplete,选择选项后,在「Selected: X」区域显示选中选项的具体数量。

解决方案代码

import React from "react";
import ClickAwayListener from "@mui/material/ClickAwayListener";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import Checkbox from "@mui/material/Checkbox";
import DeleteIcon from "@mui/icons-material/Delete";

const icon = <span>☐</span>;
const checkedIcon = <span>☑</span>;

const LabelPopper = (props) => {
  return <Box {...props} />;
};

export default function ClickAway() {
  const [open, setOpen] = React.useState(false);
  // 初始化选中值为空数组(适配多选模式)
  const [value, setValue] = React.useState([]);

  const handleValidation = () => {
    console.log("select at least one");
    setValue([]);
  };
  const clearIcon = <DeleteIcon onClick={handleValidation} fontSize="small" />;

  const handleClick = () => {
    setOpen((prev) => !prev);
  };

  const handleClickAway = () => {
    setOpen(false);
  };

  // 全选逻辑:选中除"Select All"外的所有选项
  const handleSelectAll = () => {
    const allOptionsExceptSelectAll = top100Films.filter(
      film => film.title !== "Select All"
    );
    setValue(allOptionsExceptSelectAll);
  };

  return (
    <>
      <ClickAwayListener onClickAway={handleClickAway}>
        <Box sx={{ position: "relative" }}>
          <div>
            <button type="button" onClick={handleClick}>
              Open menu dropdown
            </button>
          </div>
          {open ? (
            <Box sx={{ padding: 2, border: "1px solid #ccc", marginTop: 1 }}>
              <div>
                <div>
                  <button
                    style={{ marginBottom: 16 }}
                    type="button"
                    onClick={handleSelectAll}
                  >
                    select all
                  </button>
                </div>
                {/* 显示选中选项的数量 */}
                <span style={{ marginBottom: 16, display: "block" }}>Selected: {value.length}</span>
                <Autocomplete
                  multiple
                  id="checkboxes-tags-demo"
                  open
                  limitTags={1}
                  options={top100Films}
                  disableCloseOnSelect
                  clearIcon={clearIcon}
                  getOptionLabel={(option) => option.title}
                  // 监听选中值变化,更新状态
                  onChange={(event, newValue) => {
                    setValue(newValue);
                  }}
                  renderOption={(props, option, { selected }) => {
                    return (
                      <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="Favorites"
                      InputProps={{
                        ...params.InputProps,
                        endAdornment: null
                      }}
                    />
                  )}
                  PopperComponent={LabelPopper}
                  value={value}
                />
              </div>
            </Box>
          ) : null}
        </Box>
      </ClickAwayListener>
    </>
  );
}

const top100Films = [
  { title: "Select All", value: false },
  { 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 },
  {
    title: "The Lord of the Rings: The Return of the King",
    year: 2003
  },
  { title: "The Good, the Bad and the Ugly", year: 1966 },
  { title: "Fight Club", year: 1999 },
  {
    title: "The Lord of the Rings: The Fellowship of the Ring",
    year: 2001
  },
  {
    title: "Star Wars: Episode V - The Empire Strikes Back",
    year: 1980
  },
  { title: "Forrest Gump", year: 1994 },
  { title: "Inception", year: 2010 },
  {
    title: "The Lord of the Rings: The Two Towers",
    year: 2002
  },
  { title: "One Flew Over the Cuckoo's Nest", year: 1975 },
  { title: "Goodfellas", year: 1990 },
  { title: "The Matrix", year: 1999 },
  { title: "Seven Samurai", year: 1954 },
  {
    title: "Star Wars: Episode IV - A New Hope",
    year: 1977
  },
  { title: "City of God", year: 2002 },
  { title: "Se7en", year: 1995 },
  { title: "The Silence of the Lambs", year: 1991 },
  { title: "It's a Wonderful Life", year: 1946 },
  { title: "Life Is Beautiful", year: 1997 },
  { title: "The Usual Suspects", year: 1995 },
  { title: "Léon: The Professional", year: 1994 },
  { title: "Spirited Away", year: 2001 },
  { title: "Saving Private Ryan", year: 1998 },
  { title: "Once Upon a Time in the West", year: 1968 },
  { title: "American History X", year: 1998 },
  { title: "Interstellar", year: 2014 }
];

关键修改点

  • 将value的初始值改为空数组,适配Autocomplete的多选模式
  • 给Autocomplete添加onChange事件,实时更新选中的选项数组
  • 将Selected: X替换为Selected: {value.length},直接显示选中数组的长度
  • 实现handleSelectAll函数,处理全选按钮的逻辑,过滤掉"Select All"选项后设置为选中值
  • 给Autocomplete绑定value属性,确保选中状态与组件状态同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:25:19