This is the first day of my participation in the August Challenge. For details, see:August is more challenging

One, foreword

My youth camp series is only used to share knowledge summarization note-taking techniques, rather than teaching templates, you are welcome to point out any questions.

I have a small belt, since the last update after the article, has been preparing for the problem about the college, so for a long time did not see the code and technical posts, almost once forgot what is the front end. But! By chance, I found the byte to arrange the front end of the youth training camp activities, then hold a try to have a psychological to sign up, and then I entered (dog head). The lessons at the youth camp were very interesting. Byte’s technicians came to take lessons and gave us homework. In this part study and part review. Do some previous technical summary and new learned things (incidentally Dally August more text (dog head)).

Second, the body

In the youth training camp, we had to make something for demonstration, but in the technology selection of our group, because everyone’s technology stack is different, so we chose CSSinJS framework (I am the only one who can’t do it).

1. What isCSSinJS

Literally, it’s writing CSS in JS, but why does it matter? As I understand it, CSSinJS is written specifically for React. The reason is:

  1. ReacthtmlThe fusion is great (JSX) but forCSSAlmost no (poor) integration
  2. inReactIn the writingCSSOften appearThe style of pollution,It is difficult to reuse,Redundant codeProblems, etc.

In response to this phenomenon, many folk MOBS revolted and encapsulated React with a series of third-party libraries to enhance CSS. One of the dark horses, the Mustang, was Styled – Components.

2.styled-componentsintroduce

For the Styled Components, I think:

  • willcssI can write it and reduce my learning costs
  • withJSCSS(variables, function methods)
  • Styles are incorporated into components to avoid problems such as style contamination and on-demand loading

(1) to download

# with npm
npm install --save styled-components

# with yarn
yarn add styled-components
Copy the code

Official advice:

It is highly recommended (but not required) to use the Babel plug-in as well. It provides many benefits, such as clearer class names, server-side rendering compatibility, smaller packages, and more.

(2) use

Import it in the component file that you want to use:

import styled from "styled-components";
Copy the code

Look at the document, rough use up

Style Components

import styled from "styled-components";

// Define the style variable
const applered = "#e74c3c";

// Create the style component
// Const Style component name = Styled. Created element '// Style content' (template string)
export const C1Button = styled.button `
    padding: 12px 24px;
    border: 1px solid ${applered};
    background: #FFFFFF;
    border-radius: 5px;
    color: ${applered};
    outline: none;
    font-size: 14px;
`;

export default class Demo extends Component{
    render(){
        return (
            <div>// Use the style component<C1Button>Hello world</C1Button>
            </div>)}}Copy the code

You get a big red onebutton

To add attributes to an element of a style component, use the attr method:

import styled from "styled-components";

// Add attributes to the input tag using the attr method
export const NavSearch = styled.input.attrs({
    placeholder: 'search'.type: 'text',})`
    width: 160px;
    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;
    The ${//Pseudo-classes or pseudo-elements can be defined using methods like sass or less.
    &::placeholder {
        color: #999;
    }
    &.focused {
        width: 240px;
    }
Copy the code

You get a gray input box:

Global style

To set the global style in stylELd-Components, you need to import createGlobalStyle

import styled, {createGlobalStyle} from "styled-components";

// Global style
export const globleStyle = createGlobalStyle ` *{margin: 0; padding: 0} `;

export default class Demo extends Component{
    render(){
        return (
            <div>// At the top of the component tree, the global style is automatically injected during rendering<globleStyle></globleStyle>
            </div>)}}Copy the code

But this is a bit of a sissy, and can be replaced with app.css.

Image import

For components that need to import images, we can import the images and add them to the style component as variables. Such as:

import styled from "styled-components";
// Import the image
import logo from '.. /logo.svg';

// Create the IMG tag style component
export const LogoImg = styled.img.attrs({
    src: logo,      // Import the image
    alt: "no_img",})` width: 200px; border: 1px solid blue; border-radius: 5px; Box-shadow: 5px 5px 5px rgba(0,0,0,.3); `;

export default class Demo extends Component{
    render(){
        return (
            <div>
                <LogoImg></LogoImg>
            </div>)}}Copy the code

Get a nice React logo:

Style component inheritance

When the components are more, there are more styles to write, so it will take a lot of effort to write. Styled – Components provide the capability to inherit style components. The child tag is the same as the parent tag and has the same style. However, the child tag can be overwritten or added by itself.

import styled from "styled-components";

// Create a parent div style component
export const parentDiv = styled.div ` padding: 12px; border-radius: 5px; color: #4c4c4c; background: #e74c3c; `;


// Create a child div style component inherited from parentDiv
// Const style component = styled(parent Style component);
export const childDiv = styled(parentDiv) ` color: green; background: #f1c40f; `;

export default class Demo extends Component{
    render(){
        return (
            <div>
                <parentDiv>
                    <p>This is a text on parent div.</p>
                    <childDiv>
                        <p>This is a text on child div.</p>
                    </childDiv>
                </parentDiv>
            </div>)}}Copy the code

The child div overrides the color and background while retaining the parent’s border-RADIUS and padding:

animation

In native CSS, animations are defined via @keyFrames, and the KeyFrames feature is provided in Styled – Components for creating animations.

/ / import
import styled ,{keyframes} from "styled-components";

// Create an animation
const rotate = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `;

// Create a div style component
export const Windmill = styled.div `
    display: inline-block;
    The ${//Add an animation to a component}
    animation: ${rotate}2s linear infinite; padding: 2rem 1rem; The font - size: 1.2 rem; `

export default class Demo extends Component{
    render(){
        return (
            <div>
                <Windmill>&lt; 💅 &gt;</Windmill>
            </div>)}}Copy the code

Got a lovely spinning ice cream bar:

Props and participation

For the Softel-Components function, props are derived from functions, and the teradic operator or its value can be used to create a different effect:

/ / import
import styled from "styled-components";

/ / props
export const Button = styled.button<any> `
    padding: 12px 24px;
    border-radius: 5px;
    The ${//Don't be like me. It's tiring and inefficient.
    border: 1px solid ${(props : any) => props.primary ? "blue" : props.danger ? "red" :  props.warning ? "orange" : props.info ? "black" : props.success ? "green" : "blue"};
    background: ${(props : any) => props.fill ? props.primary ? "blue" : props.danger ? "red" :  props.warning ? "orange" : props.info ? "black" : props.success ? "green" : "#c0c0c0" : "white"};
    color: ${(props : any) => props.fill ? "white" : props.primary ? "blue" : props.danger ? "red" :  props.warning ? "orange" : props.info ? "black" : props.success ? "green" : "blue"};
    outline: none;
    font-size: 14px;
    margin: 6px;
    cursor: pointer;
    transition: all .2s ease-in-out;
    &:hover{
        color: ${(props : any) => props.fill ? props.primary ? "blue" : props.danger ? "red" :  props.warning ? "orange" : props.info ? "black" : props.success ? "green" : "#c0c0c0" : "white"};
        background: ${(props : any) => props.fill ? "white" : props.primary ? "blue" : props.danger ? "red" :  props.warning ? "orange" : props.info ? "black" : props.success ? "green" : "blue"};
    }
    &::after{
        content:"";
    }
`;

export default class Demo extends Component{
    render(){
        return (
            <div>
                <Windmill>&lt; 💅 &gt;</Windmill>
            </div>)}}Copy the code

Get a variety of buttons:

conclusion

Styled – Components are a good choice for React’s CSS, but are not the optimal solution. What I think are the shortcomings of Styled – Components:

  • Each style label is bound to a style (even if you inherit well), which requires making many style components that are not easy to view.
  • Not very friendly to those who want to do special effects or animation, style changes

Come to the conclusion: I still like Sass

The last

If there is any problem, I hope you can tell me so that I can timely correct. My youth camp article was written as a personal study note. It’s a sprint before school starts.

New on the road, also please include. I’m MoonLight, a cub.