Norman's Note 諾曼筆記

Norman's Note 諾曼筆記

styled-components 筆記

如果 className={className} 的 reassign 沒有在 functional component 的第一層

可以在使用的時候多包一層 div,來限制它的寬度,或是 > div reassign 真正的第一層 CSS

&& ampersand

the ampersand can be used to increase the specificity of rules on the component; this can be useful if you are dealing with a mixed styled-components and vanilla CSS environment where there might be conflicting styles
https://styled-components.com/docs/basics
看起來是用更多 className 讓權重變更高,instead of using !important

"as" polymorphic prop

可以條件式的把你 style 好的 component 換成其他 component
https://styled-components.com/docs/api#as-polymorphic-prop
https://styled-components.com/docs/basics#extending-styles

createGlobalStyle

寫各種泛用的 className 在這裡
https://styled-components.com/docs/api#createglobalstyle

Apply styled() to a Functional component

在 functional components 加上 className={className},把 className pass 下去才會 apply style

ampersand &

https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting

Nesting

https://styled-components.com/docs/faqs#can-i-nest-rules

  a {
    text-decoration: none;
  }
  &:first-child {
    margin: 0;
  }
  • 增加空白
&::before,
&::after {
  content: ' ';
}
  • 變換 html tag as="div"

  • margin: auto 推到底的意思

  • 從某個 className 作為起始 style
const Input = styled.input.attrs({
  className: 'custom-class-name',
})`
  • attrs 也可以帶 function,第一個參數是 props
const Input = styled.input.attrs(props => ({
  className: props.$isCertainCondition ? CLASSNAMEs.CUSTOM_CLASS_02 : CLASSNAMEs.CUSTOM_CLASS_01,
}))`

transient props

props name 加上 $ dollar sign 的原因:

  • Note the dollar sign ($) prefix on the prop; this marks it as transient and styled-components knows not to add it to the rendered DOM element or pass it further down the component hierarchy.
const Comp = styled.div`
  color: ${props => props.$fg || 'black'};
`;

render(<Comp $fg="red">I'm red!</Comp>);