每个都有不同的用例吗?什么时候应该使用 withStyles 而不是 makeStyles?
我刚刚开始使用 Material UI,我知道它使用 CSS in JS 样式组件的方式。
我在如何创建样式的文档中看到了 2 种方法:
使用sx道具:
<Box sx={{ backgroundColor: 'green' }}/>
Run Code Online (Sandbox Code Playgroud)
使用makeStyles方法:
makeStyles({
root: {
backgroundColor: 'green'
}
})
Run Code Online (Sandbox Code Playgroud)
我知道 JS 中的 CSS 比原生 CSS 性能低得多。
但是在我刚刚编写的这两种方法中,哪一种更高效(如果有的话)?
顺便说一句,我使用的是 Material UI 版本 5,它声称在情感方面具有更好的整体性能而不是 JSS
在官方迁移指南中,他们给出了以下将代码从 JSS( makeStyles) 更改为新styled模式的示例。
前:
const useStyles = makeStyles((theme) => ({
background: theme.palette.primary.main,
}));
function Component() {
const classes = useStyles();
return <div className={classes.root} />
}
Run Code Online (Sandbox Code Playgroud)
后:
const MyComponent = styled('div')(({ theme }) =>
({ background: theme.palette.primary.main }));
function App(props) {
return (
<ThemeProvider theme={theme}>
<MyComponent {...props} />
</ThemeProvider>
);
}
Run Code Online (Sandbox Code Playgroud)
这对于单个类来说很好,但是当代码中有条件类时该怎么办?
例如
<main className={classnames(content, open ? contentOpen : contentClosed)}>
{/* content goes here */}
</main>
Run Code Online (Sandbox Code Playgroud)
这里,content、contentOpen和contentClosed是从 中返回的类useStyles …