CSS世界的一些问题:
- Global NameSpace
- Dependencies
- Dead Code Elimination
- Minification
- Sharing Constants ...
为了解决当前存在的这些CSS问题,出现了多元化的Css方案。在React中主要用的几种方案:
CSS JS独立
CSS Modules
将CSS独立成模块,Ant-design的方案,适合分模块打包
- 没有冲突
- 没有全局的作用域 :global标示全局 :local表示局部
- 从其他CSS文件导入
- 与全局类名组合
CSS in JS
JSS
利用Js来描述样式,Material-UI采用的是这个方案。 如下代码中React-JSS将component封装在高阶组件中,注入classes的属性(由于React Hook的出现,貌似当前React-JSS项目处在只读状态,作者搞了另一个hook相关的项目)
import React from 'react';
import injectSheet from 'react-jss';
const styles = {
button: {
background: props => props.color
},
label: {
fontWeight: 'bold'
}
}
const Button = ({classes, children}) => (
<button className={classes.button}>
<span className={classes.label}>
{children}
</span>
</button>
});
export default injectSheet(styles)(Button)
一个典型的应用是在theme主题上,将React应用包装在ThemeProvider中。
const Button = withTheme(({theme}) => (
<button> I can access {theme.colorPrimary} </button>
));
const StyledButton = injectSheet(styles)(Button)
const theme = {
colorPrimary: 'green'
};
const App = () => (
<ThemeProvider theme={theme}>
<StyledButton>I am a button with green</StyledButton>
</ThemeProvider>
)
优点:
- Theme的支持
- Lazy加载,style只会在组件mount的适合创建
- 自动的绑定和解绑,当没有组件使用时会被移除DOM
- 组件之间可以共享一份样式
Styled-components
写法:
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: ${props => props.primary ? 'SteelBlue':'palevioletred'};
`;
<Title primary>Hello World</Title>
优点大致如下:
- 可继承性
- Theming,同样也有ThemeProvider,并且是函数式themes,不需要组件
import {withTheme} from 'styled-components'
class MyComponent extends React.Component {
render() {
this.props.theme;
...
}
}
export default withTheme(MyComponent)
- 动画
Radium
Radium is a set of tools to manage inline styles on React elements. It gives you powerful styling capabilities without CSS. Support for CSS pseudo selectors, media queries, vendor-prefixing, and much more through a simple interface