我正在尝试使用 tailwind 在 @mui/material/drawer 组件中添加样式。
import { Close } from "@mui/icons-material";
import { Box, Drawer, IconButton, TextField } from "@mui/material";
import { useContext} from "react";
import { SearchContext } from "store/context";
export default function SearchDrawer() {
const { search, setSearchMode } = useContext(SearchContext);
return (
<Drawer open={search.searchMode} anchor="bottom">
<Box sx={{ height: "100vh" }} className="bg-red-500">
<IconButton onClick={() => { setSearchMode(!search.searchMode); }}><Close/></IconButton>
<div>
<TextField variant="outlined" sx={{display: 'block'}}/>
<TextField variant="outlined" sx={{display: 'block'}}/>
</div>
</Box>
</Drawer>
);
}
预期的行为是
<Box sx={{ height: "100vh" }} className="bg-red-500">
这行代码会使整个屏幕变红,但什么也没有发生。 Tailwind 样式不适用于某些 Material-ui 组件,如“抽屉”、“对话框”、“工具提示”,所有这些组件都悬停在其他组件上。
Tailwindcss 类在工具提示和对话框组件中不起作用 #33424 - GitHub
本页说修改material-ui主题,
defaultProps: {
container: rootElement,
},
},
但是 rootElement 在 Reactjs 中是可用的,如何在 Nextjs 上做。
这是官方文档对我有用的:
在您的文件tailwind.config.js中添加以下内容:
//Remove Tailwind CSS's preflight style so it can use the MUI's preflight instead
corePlugins: {
preflight: false,
},
在您的文件tailwind.config.js中添加以下内容(对于nextjs添加#__next):
//Add the important option, using the id of your app wrapper. For example, #__next for Next.js and "#root" for CRA
important: '#__next',
你的文件 tailwind.config.js 应该像:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
//Add the important option, using the id of your app wrapper. For example, #__next for Next.js and "#root" for CRA
important: '#__next',
theme: {
extend: {},
},
plugins: [],
//Remove Tailwind CSS's preflight style so it can use the MUI's preflight instead
corePlugins: {
preflight: false,
},
}
import * as React from 'react';
import { StyledEngineProvider } from '@mui/material/styles';
export default function GlobalCssPriority() {
return (
<StyledEngineProvider injectFirst>
{/* Your component tree. Now you can override MUI's styles. */}
</StyledEngineProvider>
);
}
可以查看官方文档:https://mui.com/material-ui/guides/interoperability/#tailwind-css
对于 NextJS,您必须在回调中包装“getElementById”:
MuiDrawer: {
defaultProps: {
// container: document.getElementById("__next"), // ❌ Wrong
container: () => document.getElementById("__next"), // ✅ Correct
},
},
请记住,您必须对您使用的所有悬停组件(抽屉、对话框等)执行此操作:
const rootElement = () => document.getElementById("__next");
export const theme = createTheme({
// ...
MuiPopover: {
defaultProps: {
container: rootElement,
},
},
MuiPopper: {
defaultProps: {
container: rootElement,
},
},
MuiDrawer: {
defaultProps: {
container: rootElement,
},
},
MuiModal: {
defaultProps: {
container: rootElement,
},
},
// ... and all the other hover components