文章目錄
problems and solutions
影片說的很清楚目前模組化的前端,很難知道說 css 會作用到那些 element。
styled-components 101
- tagged template literals. it’s a part of JavsScript language.
- styled-components 不需要使用到 className
- styled-components is a CSS-in-JS solution with a radical idea: every style is also a React component.
- global styles are baseline defaults that are very low specificity, so they will always be overwritten by any explicitly-set styles.
作者認爲 css in JS 這術語取名不好:The name “CSS-in-JS” has always bothered me—it’s a misnomer! It makes it sound like we’ve come up with some pure-JavaScript way of doing styling. Nothing could be further from the truth: we’re still writing 100% full-fat real-world CSS. JS is the delivery mechanism for our CSS, that’s all.
- the
styled
object has methods for every HTML tag (at least, the ones typically used within the<body>
). Examples will frequently usestyled.div
, but it’s important to point out that there is alsostyled.a
,styled.cite
,styled.canvas
,styled.marquee
, and so on.
If you’re interested in learning more about how styled-components works, I wrote a blog post called “Demystifying styled-components”. Demystifying styled-components
- Server-side Rendering
- Learning how to integrate styled-components into your SSR process is beyond the scope of this course, but here are some links to help you get set up:
- Styled Components | Gatsby
- styled-components: Advanced Usage
Global styles
styled-components has a specific API for creating global styles:
|
|
When the GlobalStyles component is rendered, it will inject all of its CSS into the <head>
of the document, applying those styles.
css reset
global styles
- You can see the baseline set of global styles I personally use in new projects over in the Treasure Trove: My Global Styles • Treasure Trove • Josh W Comeau’s Course Platform
Dynamic Styles
The official styled-components way of managing dynamic styles is to use interpolation functions:
|
|
CSS Variables, Media queries
|
|
|
|
component libraries
breadcrumbs
Josh 他先去 Breadcrumb Example | APG | WAI | W3C 使用 devTools 觀察 html 結構,然後再實作。
Composition (Button)
we’ll see how to use the polymorphic as prop to dynamically change the tag that styled-components renders.
Dynamic tags 動態的 HTML tag
- “as” polymorphic prop styled-components: API Reference
Here’s another quick example, this time using React Router’s Link instead of a plain anchor:
|
|