Norman's Note 諾曼筆記

Norman's Note 諾曼筆記

styled-components 筆記

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>);