一起使用 Joy UI 和 Material UI
了解如何在同一项目中一起使用 Joy UI 和 Material UI。
简介
将它们一起使用主要有两种用例
- 您现有的项目已经使用了 Material UI,但您愿意探索 Joy UI 提供的全新组件和样式。
- 您已使用 Joy UI 启动了项目,但发现缺少您需要的关键组件。
此外,将它们一起使用时请记住以下几点
- 它们都使用 MUI System 作为其样式引擎,后者使用 React 上下文进行主题设置。
- 主题作用域必须在其中一个库上完成。
先决条件
- 在您的项目中安装了
@mui/material
和@mui/joy
。 - 两个库的版本必须是 v5.12.0 或更高版本。
设置 providers
在 Material UI 的 ThemeProvider
内部渲染 Joy UI 的 CssVarsProvider
,并使用 THEME_ID
将主题彼此分开。
import {
createTheme,
ThemeProvider,
THEME_ID as MATERIAL_THEME_ID,
} from '@mui/material/styles';
import { CssVarsProvider as JoyCssVarsProvider } from '@mui/joy/styles';
import CssBaseline from '@mui/material/CssBaseline';
const materialTheme = createTheme();
export default function App() {
return (
<ThemeProvider theme={{ [MATERIAL_THEME_ID]: materialTheme }}>
<JoyCssVarsProvider>
<CssBaseline enableColorScheme />
...Material UI and Joy UI components
</JoyCssVarsProvider>
</ThemeProvider>
);
}
同步颜色模式
要在 providers 之间同步颜色模式,请从两个库中调用 setMode
import { useColorScheme as useJoyColorScheme } from '@mui/joy/styles';
import { useColorScheme as useMaterialColorScheme } from '@mui/material/styles';
const ModeToggle = () => {
const { mode, setMode: setMaterialMode } = useMaterialColorScheme();
const { setMode: setJoyMode } = useJoyColorScheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
// prevent server-side rendering mismatch
// because `mode` is undefined on the server.
return null;
}
return (
<IconButton
onClick={() => {
setMaterialMode(mode === 'dark' ? 'light' : 'dark');
setJoyMode(mode === 'dark' ? 'light' : 'dark');
}}
>
{/** You can use `mode` from Joy UI or Material UI since they are synced **/}
{mode === 'dark' ? <DarkMode /> : <LightMode />}
</IconButton>
);
};
注意事项
两个库具有相同的类名 prefix
import MaterialTypography, {
typographyClasses as materialTypographyClasses,
} from '@mui/material/Typography';
import JoyTypography, {
typographyClasses as joyTyographyClasses,
} from '@mui/joy/Typography';
import Stack from '@mui/material/Stack';
<Stack
sx={{
// similar to `& .${joyTyographyClasses.root}`
[`& .${materialTypographyClasses.root}`]: {
color: 'red',
},
}}
>
{/* Both components are red. */}
<MaterialTypography>Red</MaterialTypography>
<JoyTypography>Red</JoyTypography>
</Stack>;
Joy UI 和 Material UI 组件对于 主题化组件 有不同的名称。例如,Joy UI 的 Button 使用 JoyButton
,而 Material UI 的 Button 使用 MuiButton
。