Styled Components I have read quite a few articles for the Style network, but I can’t find anything that strikes a chord with me, so I will write one myself
When writing business code, we often encounter inconsistent front-end naming conventions and back-end interface returns, and we need to do a lot of annoying transformations in our code, such as
fetch().thne(resp= > {
this.userName = resp.user_nick_name;
})
Copy the code
We need this adaptation to convert “user_nick_name” to “userName” in order to put the data from the back end into various components and stores in the front end. This is a mapping. This binds the mapping of the data at the front and back ends.
If you think outside the box a little bit, you’ll find that CSS and DOM are bound by this mapping to make styles work.
<div class="red-button"></div>
Copy the code
The above code is completely separate from THE DOM and CSS. We bind the KEY to the DOM in the CSS style using class=”red-button” to make the style work. It’s nice to write this way, because the style is separate from the DOM, and it’s easier to maintain in isolation.
But the problem is that the class=”red-button” binding, when I look for the. Red-button specific style, if the project directory structure is more formal, it is convenient to find the CSS file, and then search the. Red-button, locate the red button style code, it is OK. But if the project directory structure is not canonical,.red-button may be defined anywhere throughout the project. This is the trouble, I will generally direct global search, not so comfortable.
At this point someone will say CSS-modules, which lets you import CSS as JSON objects just like you import JS. In this case, CSS files are easy to find.
import styles from './style.css';
Copy the code
But have you ever wondered why we need div, why we need class= for binding mappings.
Have you ever wondered what the most direct expression of the red button is? The answer is simple. It’s just a red button.
<RedButton />
Copy the code
I feel like it’s a bit awkward to write “className=”button”, calss=”button”, class={styles.button} on JSX or DOM, repeating class=, isn’t it?
Take a look at the following code:
.red-button {
color: red;
}
<div class="red-button"></div>
Copy the code
Should we focus on whether the DOM element is a div tag or a button tag? Obviously not. It’s all superfluous stuff.
Styled – Components, the tiresome binding process disappears, and the class= binding style syntax is no longer seen.
const RedButton = styled.div` color: red; `;
<RedButton />
Copy the code
As above, this is why I use styled- Components.
Taobao front-end 2020 enrollment is underway ~~~ if you are the class of 20 graduates, and front-end skills are good, you can scan the code to push oh