【问题标题】:What is the advantage of using makeStyles over in-line styles or css classes?与内联样式或 css 类相比,使用 makeStyles 有什么优势?
【发布时间】:2020-12-20 06:04:48
【问题描述】:

当您可以使用 style 属性为组件设置内联样式或在 css 文件中定义类并使用 className 属性时,为什么要使用 makeStyles?

【问题讨论】:

    标签: material-ui


    【解决方案1】:

    下面是简单的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"
        }
      }
    }));
    
    

    如果我错了,请纠正我。

    【讨论】:

    • 据我所知...style-in-JS 可能很快就会消失...但是 vanilla css 会持续很长时间...另外 js 样式的学习曲线很陡峭...作为一个习惯写 css 的人,我应该切换到 js 样式吗?
    • 这取决于您的需求。如果您正在考虑使用 @material-ui 包。然后使用jss 是最好的选择。但是,当然,您可以使用外部或原版 CSS 做同样的事情。尽管某些类似 css 的属性,但无法使用 jss 复制。这就是为什么在我看来拥有这两个领域的知识是件好事。
    猜你喜欢
    • 2012-05-02
    • 2010-09-24
    • 2010-12-27
    • 2015-04-06
    • 2013-05-09
    • 2017-05-29
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多