【发布时间】:2020-12-20 06:04:48
【问题描述】:
当您可以使用 style 属性为组件设置内联样式或在 css 文件中定义类并使用 className 属性时,为什么要使用 makeStyles?
【问题讨论】:
标签: material-ui
当您可以使用 style 属性为组件设置内联样式或在 css 文件中定义类并使用 className 属性时,为什么要使用 makeStyles?
【问题讨论】:
标签: material-ui
下面是简单的sandbox 显示和解释为什么(据我所知)使用makeStyles 优于内联样式 (style={{}}) 以及使用外部css 的常规方式文件(使用className="someClassname")
makeStyles
theme属性(颜色、排版等)in-line 样式的使用theme属性(颜色、排版等)external/imported CSS 文件的使用theme属性(颜色、排版等)import React from "react";
import "./styles.css";
import { makeStyles, useTheme } from "@material-ui/core/styles";
export default function App() {
const classes = useStyles();
const theme = useTheme();
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Material-UI Styling</h2>
<div>
<h3>A. Use of makeStyles</h3>
<p>+ possible of using nested styling</p>
<p>+ possible of using theme attributes (color, typography and etc)</p>
<ul className={classes.list}>
<li>list one</li>
<li>list two</li>
<li>list three</li>
</ul>
</div>
<div>
<h3>B. Use of in-line styles</h3>
<p>- not possible using nested styling</p>
<p>+ possible of using theme attributes (color, typography and etc)</p>
<ul
style={{
backgroundColor: theme.palette.primary.light,
"& li": {
color: "yellow"
}
}}
>
<li>list one</li>
<li>list two</li>
<li>list three</li>
</ul>
</div>
<div>
<h3>C. Use of imported CSS file</h3>
<p>- not possible using nested styling</p>
<p>
- not possible to use theme attributes (color, typography and etc)
</p>
<ul className="list">
<li>list one</li>
<li>list two</li>
<li>list three</li>
</ul>
</div>
</div>
);
}
const useStyles = makeStyles((theme) => ({
list: {
backgroundColor: theme.palette.secondary.light,
"& li": {
color: "yellow"
}
}
}));
如果我错了,请纠正我。
【讨论】:
@material-ui 包。然后使用jss 是最好的选择。但是,当然,您可以使用外部或原版 CSS 做同样的事情。尽管某些类似 css 的属性,但无法使用 jss 复制。这就是为什么在我看来拥有这两个领域的知识是件好事。