React教程(九) : Styled Component


官網地址:https://styled-components.com/docs/basics

使用Styled Component的幾大理由
1)Scoped Style(范圍限定的樣式)
不用擔心引用的css文件被其他人修改

2)CSS in JS
可以在JS中使用component內部變量做條件判斷

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};
`;
<Button primary>Normal</Button>

3)可移植性
沒有了css,所有樣式都在組件內部,方便移植到其他平台,如React Native。

4)沒有了樣式命名的沖突
沒有class name的沖突,適用於微前端架構。 因為微前端的一大問題就是不用sub app之間可能定義了相同名稱的樣式。 而style component的class name是通過hash算法得出的,不會沖突。

5)便於對樣式做unit test
通過style-components團隊提供的組件
npm install --dev jest-styled-components
我們可以進行如下的單元測試

import React from 'react'
import styled from 'styled-components'
import renderer from 'react-test-renderer'
import 'jest-styled-components'
const Button = styled.button`
  color: red;
`
test('it works', () => {
  const tree = renderer.create(<Button />).toJSON()
  expect(tree).toMatchSnapshot()
})

一句話總結:CSS-IN-JS
代碼示例: https://github.com/992990831/modernization/tree/main/responsive-layout

常用API
1: styled - 基礎API,生成組件
2: attrs - 為組件添加屬性(Props)

const Input = styled.input.attrs(props => ({
  // we can define static props
  type: "text",
  // or we can define dynamic ones
  size: props.size || "1em",
}))`

3: as - 轉變組件類型,比如將一個div轉變為button

const Component = styled.div`
  color: red;
`;

render(
  <Component
    as="button"
    onClick={() => alert('It works!')}
  >
    Hello World!
  </Component>
)

4: css - 避免創建新的組件,直接應用樣式。 需要修改babel。

<div
  css={`
    background: papayawhip;
    color: ${props => props.theme.colors.text};
  `}
/>
<Button
  css="padding: 0.5em 1em;"
/>

參考:https://styled-components.com/docs/tooling#babel-plugin

5: TypeScript兼容
To prevent TypeScript errors on the css prop on arbitrary elements, install @types/styled-components and add the following import once in your project:
import {} from 'styled-components/cssprop'

6: createGlobalStyle - 創建並應用全局樣式

7: ThemeProvider

8: keyFrames - 創建動畫

import styled, { keyframes } from 'styled-components'

const fadeIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`

const FadeInButton = styled.button`
  animation: 1s ${fadeIn} ease-out;

問題及答復
1)有同事問,Styled-Component的CSS都分散在各個組件中,不能像傳統CSS文件那樣有個總的樣式,豈不是很麻煩?
答復:styled-components提供了createGlobalStyle方法,可以創建global樣式。代碼示例如下:
新建src/styles/global.js

import { createGlobalStyle } from "styled-components";
import px2vw from "../utils/px2vw";
export const Global = createGlobalStyle`
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  :root {
      font-size: ${px2vw(24)};

      @media (min-width: 768px) {
        font-size: ${px2vw(18)};
      }

      @media (min-width: 1024px) {
        font-size: ${px2vw(16)};
      }
    }
`;

export default Global;

在App.js中引用該Global樣式

import Global from "./styles/global";
function App() {
  return (
    <>
      <Global />
      <Home />
    </>
  );


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM