CSS Style 搭配React的方案

1,806 阅读2分钟

CSS世界的一些问题:

  1. Global NameSpace
  2. Dependencies
  3. Dead Code Elimination
  4. Minification
  5. Sharing Constants ...

为了解决当前存在的这些CSS问题,出现了多元化的Css方案。在React中主要用的几种方案:

CSS JS独立

CSS Modules

将CSS独立成模块,Ant-design的方案,适合分模块打包

优点:

  • 没有冲突
  • 没有全局的作用域 :global标示全局 :local表示局部
  • 从其他CSS文件导入

文件

  • 与全局类名组合

global

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>

优点大致如下:

  • 可继承性

Button

TomatoButton

  • 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

formidable.com/open-source…