我的最终目标是自定义我们的
SpeedDial
实例,以便:
对于第一部分,我发现,要永久显示标签,我必须设置
tooltipOpen
属性。这很容易。
我遇到的问题实际上是调整工具提示的样式。直接使用
sx
时我可以做得很好,但我无法以可重用的方式实现这一点,例如使用 styled()
。我也不想更新全局/默认样式。
import FileCopyIcon from "@mui/icons-material/FileCopyOutlined";
import {
styled,
Box,
SpeedDial,
SpeedDialIcon,
SpeedDialAction,
} from "@mui/material";
export default function BasicSpeedDial() {
return (
<Box sx={{ height: 320, transform: "translateZ(0px)", flexGrow: 1 }}>
<SpeedDial
ariaLabel="SpeedDial basic example"
sx={{ position: "absolute", bottom: 16, right: 16 }}
icon={<SpeedDialIcon />}
>
<SpeedDialAction
icon={<FileCopyIcon />}
tooltipTitle="Copy the File"
tooltipOpen
sx={{
"& .MuiSpeedDialAction-staticTooltipLabel": {
width: "8rem",
},
}}
/>
<SDA1
icon={<FileCopyIcon />}
tooltipTitle="Copy the File"
tooltipOpen
/>
<SDA2
icon={<FileCopyIcon />}
tooltipTitle="Copy the File"
tooltipOpen
/>
</SpeedDial>
</Box>
);
}
const SDA1 = styled(SpeedDialAction)({
"& .MuiSpeedDialAction-staticTooltipLabel": {
width: "8rem",
},
});
const SDA2 = styled(SpeedDialAction)({
root: {
"& .MuiSpeedDialAction-staticTooltipLabel": {
width: "8rem",
},
},
});
结果是:
如你所见,我似乎无法制作 SpeedDialAction
的
styled版本。我可以使用带有图标、标签和单击操作的对象数组,但我确实想更好地了解整个
sylted
方法的工作原理。
每当我想出一些关于该方法的东西时,我想我就去做了,但它在下一种情况下就不起作用了。
例如,下面是我们成功创建样式化可重用 Chip
组件的代码示例:
const CancelledChip = styled(Chip)(({ theme }) => ({
backgroundColor: lighten(theme.palette.error.main, 0.9),
color: theme.palette.error.main,
"& .MuiChip-icon": {
color: theme.palette.error.main,
},
}));
我已经确认,静态样式(没有
theme
)似乎不会改变行为。
我错过了什么?
TL;DR:
useTheme
+ useMemo
+ 'stylesOverrides'
我遇到了类似的问题。
styled
函数将其样式应用于组件的根,但不应用于子元素或伪元素,工具提示就是其中之一。
这给我们留下了
sx
属性,您不想使用它或与 stylesOverrides
一起使用。为了使后者可重用,您可以提供快速拨号操作主题提供程序,它会覆盖工具提示样式。以下是与我使用的类似的快速拨号组件,因此您可能需要根据您的用例进行调整:
import FileCopyIcon from '@mui/icons-material/FileCopyOutlined';
import SpeedDial from '@mui/material/SpeedDial';
import SpeedDialAction from '@mui/material/SpeedDialAction';
import SpeedDialIcon from '@mui/material/SpeedDialIcon';
import { createTheme, ThemeOptions, ThemeProvider, useTheme } from '@mui/material/styles';
import { useMemo } from 'react';
const speedDialActionOverrides: ThemeOptions = {
components: {
MuiSpeedDialAction: {
styleOverrides: {
staticTooltipLabel: {
whiteSpace: 'nowrap',
},
},
},
},
};
const TestDial = () => {
// extend the existing theme with some overrides
const existingTheme = useTheme();
const theme = useMemo(() => createTheme(existingTheme, speedDialActionOverrides), [existingTheme]);
return (
<ThemeProvider theme={theme}>
{/* apply the extended theme to this speed dial */}
<SpeedDial ariaLabel="Example Speed Dial" icon={<SpeedDialIcon />}>
<SpeedDialAction icon={<FileCopyIcon />} tooltipTitle="Copy the File" tooltipOpen />
</SpeedDial>
</ThemeProvider>
);
};
export default TestDial;