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

React项目中Material TreeView无法找到方形加号展开/折叠图标

解决Material UI TreeView替换为方形加减号图标问题

你可以通过两种方式实现这个需求:自定义图标组件,或者利用现有图标组合出方形加减样式。

方法一:自定义方形加减图标组件

直接创建带方形背景的加减图标组件,样式更可控:

import React from 'react';
import { Box, Typography } from '@mui/material';

// 自定义加号图标
const SquarePlusIcon = () => (
  <Box 
    sx={{
      width: 20,
      height: 20,
      border: '1px solid #666',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      borderRadius: 0.5
    }}
  >
    <Typography sx={{ fontSize: 16, fontWeight: 'bold', lineHeight: 1 }}>+</Typography>
  </Box>
);

// 自定义减号图标
const SquareMinusIcon = () => (
  <Box 
    sx={{
      width: 20,
      height: 20,
      border: '1px solid #666',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      borderRadius: 0.5
    }}
  >
    <Typography sx={{ fontSize: 16, fontWeight: 'bold', lineHeight: 1 }}>-</Typography>
  </Box>
);

在TreeView中替换图标:

<TreeView
    aria-label="file system navigator"
    defaultCollapseIcon={<SquareMinusIcon />}
    defaultExpandIcon={<SquarePlusIcon />}
    sx={{
        height: 240,
        flexGrow: 1,
        maxWidth: 400,
        overflowY: "auto",
        marginTop: "0.6rem",
    }}
>

方法二:利用Material UI现有图标组合

复用官方图标,结合Square和Add/Remove图标组合:

import SquareIcon from '@mui/icons-material/Square';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { Stack } from '@mui/material';

const SquarePlusIcon = () => (
  <Stack direction="row" alignItems="center" justifyContent="center" sx={{ position: 'relative' }}>
    <SquareIcon sx={{ fontSize: 20 }} />
    <AddIcon sx={{ fontSize: 14, position: 'absolute' }} />
  </Stack>
);

const SquareMinusIcon = () => (
  <Stack direction="row" alignItems="center" justifyContent="center" sx={{ position: 'relative' }}>
    <SquareIcon sx={{ fontSize: 20 }} />
    <RemoveIcon sx={{ fontSize: 14, position: 'absolute' }} />
  </Stack>
);

同样将这两个自定义图标传入TreeView的defaultCollapseIcon和defaultExpandIcon即可。

这两种方式都能实现你需要的方形内含加减号的树形图标效果,可根据样式需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 04:12:40