React.js |通过道具设置样式与编写 CSS-in-JS

React.js | Styling via Props vs. Writing CSS-in-JS

各种库通过组件的 props 提供样式解决方案,而长期以来的“标准”方式一直是单独编写 CSS。

随着 CSS-in-JS 的发明,现在可以拥有一些我们以前没有的好处(例如字符串文字、条件 类、扩展功能的插件等.),并且在分离级别上,它可以像 HTML 中的 CSS 样式标签一样使用,其中可以在“主”文件中定义(HTML,在这种情况下CSS) 编写代码的环境,我们有更大的灵活性,但是对于 JSS,例如,根据我的理解,将样式代码集中在 classes 对象中是一种常见的做法。

另一方面,我们不仅可以在组件中编写内联 CSS,而且各种库都提供样式解决方案作为组件的道具,例如 Material-UI.

所以,我的问题是: 与使用组件道具编写样式代码相比,您认为编写 CSS-inJS 有哪些优点和缺点?

*Disclaimer: I don't have a lot of experience with CSS-in-JS and styling in React in general, so I might have a wrong impression of what things are like generally/in the bigger picture.

*Do notice that I'm not asking about inline-CSS in components and that this is not an inline vs non-inline question, but a more specific one.

传递类。 将 CSS 之类的道具传递给组件是行不通的。

您询问 Pros/Cons 的情况:

动态className

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function App() {
  const classes = useStyles();
  return <Button className={classes.root}>My Button</Button>;
}

这只是一个更好的实现:

import './myStyle.css'

export default function App({ styleName }) {
  return <Button className={styleName}>My Button</Button>;
}

优点:

  • 简单明了。

缺点:

  • 正在编写类似 CSS 的对象(不是真实的 CSS)。
  • 这样的实现 与 UI 库分离
    • 可能有一个库可以跨项目使用,但是,为什么不使用 CSS-in-JS 呢?

CSS-in-JS

const PrettyButton = styled(Button)`
  background: linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%);
  border: 0;
  borderradius: 3;
  boxshadow: 0 3px 5px 2px rgba(255, 105, 135, 0.3);
  color: white;
  height: 48;
  padding: 0 30px;
`;

export default function App() {
  return <PrettyButton>My Button</Button>;
}

优点:

  • 写一个真正的 CSS(你会自动完成,CSS 格式化,样式检查,不写容易出错的字符串文字等)
  • CSS-in-JS 的好处(Google)。

缺点:

  • 关于为什么不使用 CSS-in-JS(Google)的争论。