Some problems in the CSS world:

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

To solve these existing CSS problems, a variety of CSS solutions have emerged. React uses the following schemes:

CSS, JS independent

CSS Modules

Independent CSS into modules, Ant-Design scheme, suitable for module packaging

  • There is no conflict
  • No global scope :global indicates global; local indicates local
  • Import from another CSS file

  • Combined with the global class name

CSS in JS

JSS

Js is used to describe styles, and Material-UI takes this approach. React-jss encapsulates components in higher-order components and injects classes properties into them.

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)
Copy the code

A typical application is to wrap the React application in ThemeProvider over the theme.

const Button = withTheme(({theme}) = > (
<button> I can access {theme.colorPrimary} </button>
));

const StyledButton = injectSheet(styles)(Button)
const theme = {
    colorPrimary: 'green'
};
const App = (a)= > (
<ThemeProvider theme={theme}>
    <StyledButton>I am a button with green</StyledButton>
</ThemeProvider>
)
Copy the code

Advantages:

  • The Theme of the support
  • Lazy-loaded, the style will only be created when the component mount is appropriate
  • Automatic binding and unbinding, removing the DOM when no component is in use
  • Components can share a style

Styled-components

Writing:

const Title = styled.h1` the font - size: 1.5 em. text-align: center; color:${props => props.primary ? 'SteelBlue':'palevioletred'};
`;
<Title primary>Hello World</Title>
Copy the code

The advantages are as follows:

  • Can be inherited

  • Theming, which also has ThemeProvider, is a functional theme and does not need a component
import {withTheme} from 'styled-components'
class MyComponent extends React.Component {
    render() { this.props.theme; . }}export default withTheme(MyComponent)
Copy the code
  • animation

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…