preface

In the development of front-end flying general, derived from a variety of frameworks, the purpose of the framework is to reduce the developer’s development difficulty, improve efficiency. The old principle of web development was separation of concerns, meaning that the various technologies were only responsible for their own domain and did not mix and form coupling. Such as HTML, CSS, JS code separation. React is a component structure that forces HTML, CSS, and JS to be written together. Such as:

const style = {
    'color': 'red',
    'fontSize': '46px'
};

const clickHandler = () => alert('hi');

ReactDOM.render(
    <h1 style={style} onclick={clickHandler}>
        Hello, world!
    </h1>,
    document.getElementById('example')
);
Copy the code

The above code is in a JS file, which encapsulates the structure, style and logic, completely violating the separation of concerns. Many people are not comfortable with React at the beginning. However, this is conducive to the isolation of components. React was used more and more, the component model became popular, and this new writing method of mixed concerns gradually became mainstream.

On the surface, React is written as a mixture of HTML, CSS, and JS. In fact, IT uses JS to write HTML and CSS. React encapsulates HTML in JSX, but what about CSS? Styled components for today.

What is styled – components

Styled – Components is a SET of CSS in JS framework for React, styled- Components. The advantage of CSS in JS over the preprocessor (Sass, less) is that CSS in JS uses THE JS syntax, and there is no need to relearn new technology, and there is no additional compilation step. It will certainly speed up your web pages. If you have experience developing SASS or Less, you can learn gravitation-Components in a few minutes.

The official documentation

1. Install

npm install --save styled-components

2. Basic usage

Styled components The most basic use of styled-components is to write styles as components, as follows:

import styled from 'styled-components';

const HomeWrapper = styled.div `
  width: 960px;
  margin: 0 auto;
  overflow: hidden;
`;
const HomeLeft = styled.div `
  float: left;
  width: 625px;
  margin-left: 15px;
  padding-top: 30px;
  .bannder-img {
    width: 625px;
    height: 270px;
  }
`;
const HomeRight = styled.div `
  float: right;
  width: 280px;
  margin-left: 15px;
  padding-top: 30px;
`;

render () {
    return (
        <HomeWrapper>
            <HomeLeft>
                left
            </HomeLeft>
            <HomeRight>
                right
            </HomeRight>
        </HomeWrapper>
    )
}
Copy the code

The above code defines three components, HomeWrapper, HomeLeft and HomeRight, so that each component has a unique style and no style contamination occurs.

2. Global styles

Each component has a unique style, so what if you need to set a global style? For styled- Components, the latest version of createGlobalStyle provides the ability to set the global style as follows:

import { createGlobalStyle } from 'styled-components'; const GrobalStyle = createGlobalStyle ` html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } @font-face { font-family: 'iconfont'; /* project id 897264 */ src: url('//at.alicdn.com/t/font_897264_7ma62sn10m3.eot'); src: url('//at.alicdn.com/t/font_897264_7ma62sn10m3.eot?#iefix') format('embedded-opentype'), url('//at.alicdn.com/t/font_897264_7ma62sn10m3.woff') format('woff'), url('//at.alicdn.com/t/font_897264_7ma62sn10m3.ttf') format('truetype'), url('//at.alicdn.com/t/font_897264_7ma62sn10m3.svg#iconfont') format('svg'); } .iconfont { font-family:"iconfont" ! important; font-size:16px; font-style:normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .clearfix:after {visibility: hidden; display: block; font-size: 0; content: "."; clear: both; height: 0; } .clearfix {zoom: 1; } `; render() { return ( <Fragment> <Provider>... </Provider> <GrobalStyle/> </Fragment> ) }Copy the code

The code GrobalStyle above is a global style component that can be introduced in the outermost layer of the React component.

3. Picture introduction

Image import is required, and an error will be reported if the import method is the same as CSS. The correct way to import is to import and then import as a variable, as follows:

import styled from 'styled-components'; import logPic from '.. /.. /statics/images/logo.png'; export const Logo = styled.div ` position: absolute; top: 0; left: 0; width: 100px; height: 56px; background-image: url(${logPic}); background-size: contain; `;Copy the code

${logPic} = ${logPic} If it is a background image, how to use the background image?

4. props

For the problem mentioned above, you can use the component’s pass value. Let’s start with an example:

recommendList.map((item) => {
    return <RecommendItem key={item} imgUrl={item}/>
})

const RecommendItem = styled.div `
  width: 280px;
  height: 50px;
  background-image: url(${(props) => props.imgUrl});
  background-size: contain;
`;
Copy the code

As you can see from the example above, the value passed by the parent component is stored in the props of the child component, so the operation should have the desired effect.

5. Label attributes

For styled components, tag attributes such as input placeholder, href of a tag, etc., are used. For styled components, the attribute attrs is provided as follows:

Style.input. Attrs ({placeholder: 'search', type: 'text'}) 'width: 30px; height: 38px; margin-top: 9px; padding: 0 40px 0 20px; box-sizing: border-box; background-color: #eee; outline: none; border: none; border-radius: 19px; color: #666; &::placeholder { color: #999; } &.focused { width: 240px; } `;Copy the code

In the above code, attrs is an object. If you need more than one attribute, add it as an object.

6. Shape components

There is a case where some components are already components and you need to add styles to them. In this case, you need to use shape components as follows:

const Link = ({className , children}) => ( <a className={className}> {children} </a> ) const StyledLink = styled(Link)` color: palevioletred; Render (<div> <Link> common component </Link> <StyledLink> add style component </StyledLink> </div>);Copy the code
7. Inheritance

If the style of a component is used in more than one place, you can’t rewrite the style in every place; the code is not elegant. For example, if a button has warning, default, primary, etc., the color of the button is different, but other styles are the same, this can be used for inheritance.

Const Button = styled. Button 'line-height: styled; display: inline-block; font-weight: 400; text-align: center; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; background-image: none; border: 1px solid transparent; white-space: nowrap; padding: 0 15px; font-size: 14px; border-radius: 4px; height: 32px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; - its - the transition: all. 3 s cubic bezier - (. 645,. 045,. 355, 1); The transition: all. 3 s cubic bezier - (. 645,. 045,. 355, 1); position: relative; -webkit-box-shadow: 0 2px 0 rgba(0,0,0,.015); Box-shadow: 0 2px 0 rgba(0,0,0,.015); Color: rgba (0, 0, 65); background-color: #fff; border-color: #d9d9d9; `; const ButtonPrimary = styled(Button)` color: #fff; background-color: #1890ff; border-color: #1890ff; `; const ButtonWarning = styled(Button)` color: #f5222d; background-color: #f5f5f5; border-color: #d9d9d9; `;Copy the code

Some people say that a common style component can be written to all styles with different classes. It works, but why not just write CSS?

Animated 8.

Here’s an example on the website:

const rotate = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `; const Rotate = styled.div` display: inline-block; animation: ${rotate} 2s linear infinite; padding: 2rem 1rem; The font - size: 1.2 rem; `; render( <Rotate>&lt; 💅 & gt; </Rotate> );Copy the code

Personally, if the animation is simple, it can be done in this way. If the animation is complicated, it is recommended to use the React-transition-group framework for better experience.

conclusion

For the styled-components, there are, of course, some other uses on the official website, for those interested, styled-components. Styled – Components will generate a class name randomly, which will not pollute global variables. Of course, maintenance will be difficult due to random generation. Expect the next version to fix this problem.