Styled – Components are used in conjunction with the React framework, enabling it to support CSS in JS writing. Such as:
const Button = styled.button`
color: grey;
`;
Copy the code
This is a simple use of SC (Styled – Components). It is convenient to create a Button component, which you can then use anywhere for the style network.
<Button>Test</Button>
Copy the code
How does all this work? Let’s break it down step by step.
Grammar rule interpretation
For those who are puzzled by SC’s odd grammar rules, how does it obtain a DOM node directly after the Styled network and then concatenate a string? For the Styled. Button, equivalent to ‘button’, is a curlized function, and the ability for function to be followed by a template string (part ‘ ‘enclosed by two backquotes) is a new feature of ES6 syntax. For example, we can use a function to receive a string as follows.
const fun = (args)=>{ console.log(args); / / /'Hello' ]
}
fun`Hello`
Copy the code
And you can add expressions in between.
const fun = (args, exp)=>{ console.log(args); / / /'Hello '.', Hi~' ]
console.log(exp); // World
}
const v = "World"
fun`Hello ${v}, Hi~`
Copy the code
A more advanced use of SC is derived from the properties you can add to expressions, such as button above. If you add a background property that changes according to props, you can write it as follows:
const Button = styled.button`
color: grey;
background: ${props => props.background};
`;
Copy the code
Just now, some people may wonder how styled. Button is equivalent to Styled (‘button’). In fact, it is simple. This allows you to use the syntax above, which is implemented in the following code.
domElements.forEach(domElement => {
styled[domElement] = styled(domElement);
});
Copy the code
Component creation process
So what does SC do after we declare a Button component in SC fashion? Select * from componentId where id = componentId; select * from componentId where id = componentId; The hash uses the MurmurHash, and the hash value is converted to a string. The generated ID is similar to sc-bDVaja
componentId = getAlphabeticChar(hash(count))
Copy the code
Insert a style node into head and return className; Create a style node and insert it into the head tag, generating a className, and insert the style from the template string into the style node. Where insertRule method
EvaluatedStyles = document.createElement(const style = document.createElement);"style");
// WebKit hack
style.appendChild(document.createTextNode(""));
document.head.appendChild(style);
const className = hash(componentId + evaluatedStyles); Style. Sheet. InsertRule ('.className { evaluatedStyles }', 0)Copy the code
Create the element based on the props and className that you resolved.
const newElement = React.createElement(
type,
[props],
[...children]
)
newElement.className = "Node generated in Part 2"
Copy the code
conclusion
The overall principle of SC is relatively simple, because it directly uses the ES6 character template feature, the resolution of the style and props sections is relatively fast, because the need to dynamically create elements and create styles during the run consumes some performance. Take the original button as an example. If the background changes once every time you click the button, you will notice that after 200 clicks, the SC will send a warning.
Over 200 classes were generated for component styled.button.
Consider using the attrs method, together with a style object forfrequently changed styles. Example: const Component = styled.div.attrs({ style: ({ background }) => ({ background, }), })`width: 100%; ` <Component />Copy the code
Warning indicates that more than 200 classes have been created. This is caused by the fact that a new Element is generated every time the background changes. At this time, we can optimize according to the prompt to directly use the style attribute of the node to modify the style, so as to avoid repeated generation of the node class.
styled.button.attrs({
style: props => ({background: props.background})
})``
Copy the code
There are many advantages to CSS in JS writing, which I won’t mention here, but the most important one is performance. The SC team has always announced to improve performance, and the V5 version has made a lot of improvements in 20 years. Of course, due to the implementation mechanism, no amount of optimization can achieve the performance of the original writing. If there is a very strict performance requirements of the website is not recommended to use, if you want to write fast write cool, SC is still a good choice. A version V5 update for Beast Mode