在我的上一个项目中,我已经开始将MUI v5与makeStyles结合使用。在部署之后,我在加载页面的CSS时遇到了巨大的延迟。因此,我开始搜索,发现在MUI v5中不推荐使用makeStyles。
梅建议用sx道具代替。这很好。但这里的问题是,我不想一起编写JSX和CSS/JSS代码。例如:
MUI是这么说的:
// App.js
function App() {
return (
<Grid sx={{ bgcolor: 'yellow', mx: 5, pt: 2, border: 1 }}>
This is a test!
</Grid>
);
}
export default App;以下是我所期望的:
// style.js
export default {
myGrid: {
bgcolor: 'yellow',
mx: 5,
pt: 2,
border: 1,
},
};// App.js
import style from "./style";
function App() {
return <Grid sx={style.myGrid}>This is a test!</Grid>;
}
export default App;我想知道在sx中独立使用JSS和JSX文件的最佳模式是什么?在另一个文件中键入VSCode道具时可以获得sx建议吗?
发布于 2022-08-04 21:28:55
您可以通过TypeScript实现这一点。如果TypeScript尚未在您的项目中配置,则必须添加它(有关此问题的帮助,请参见this SO answer )。
然后,您可以使用styles.ts类型使用所有组件样式创建一个SxProps文件。
// Styles.ts
import { SxProps } from '@mui/material'
const myGrid: SxProps = {
bgColor: 'yellow',
mx: 5,
pt: 2,
border: 1
}
export default { myGrid }通过在stlye对象上使用SxProps类型,您将获得所有MUI道具的代码完成。
发布于 2022-10-26 18:44:18
我们可以将样式存储在单个对象中。
使用Record<Keys, Type>定义父对象类型。
在那之后,当你输入关键词时,你会得到建议。等:backgroundColor
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type
//styles.ts
import { SxProps, Theme } from "@mui/material";
export const navBarStyles: Record<string, SxProps<Theme> | undefined> = {
notification: {
backgroundColor: 'white',
"&:hover, &.Mui-focusVisible": { backgroundColor: "white" }
},
test: {
color: 'green'
}
}然后导入navBarStyles
//navbar.tsx
import { navBarStyles } from '../styles/mui/navbar';应用样式
//navbar.tsx
const Navbar = () => {
return (
<IconButton sx={navBarStyles.notification}>
<KeyboardArrowDownRoundedIcon htmlColor='#ffffff' />
</IconButton>
)
}https://stackoverflow.com/questions/71992235
复制相似问题