各种库通过组件的 props 提供样式解决方案,而长期以来的“标准”方式一直是单独编写 CSS。
随着 CSS-in-JS 的发明,现在可以拥有一些我们以前没有的好处(例如字符串文字、条件类、扩展功能的插件等),并且在分离级别上,它可以像 HTML 中的 CSS 样式标签一样使用,可以在“主”文件(HTML,在 CSS 的情况下)中定义一个编写代码的环境,我们有更大的灵 active ,但是对于 JSS,例如,根据我的理解,将样式代码集中在 classes
对象中是一种常见的做法。
另一方面,我们不仅可以在组件中编写内联 CSS,而且各种库都提供样式解决方案作为组件的属性,例如 Material-UI .
所以,我的问题是: 与使用组件 Prop 编写样式代码相比,您认为编写 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.
最佳答案
您询问这些情况的优点/缺点:
动态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?
JS 中的 CSS
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 的好处(谷歌)。
缺点:
- 关于为什么不使用 CSS-in-JS 的辩论(谷歌搜索)。
关于javascript - react .js |通过 Props 设置样式与编写 CSS-in-JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59221888/