二)NextJS集成Styled Components

打开前一篇中建立的NextJS项目,添加以下依赖:
npm install babel-plugin-styled-components --save-dev
npm install styled-components --save

再添加以下内容:
1:touch .babelrc //添加babel配置文件
内容如下:

{
    "presets": ["next/babel"],
    "plugins": [["styled-components", { "ssr": true }]]
}

2: 打开pages/indes.js,替换代码如下

import styled from 'styled-components'

const Title = styled.h1`
  font-size: 50px;
  color: ${({ theme }) => theme.colors.primary};
`

export default function Home() {
  return <Title>My page</Title>
}

3:pages/_app.js, 替换代码如下

import { createGlobalStyle, ThemeProvider } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`

const theme = {
  colors: {
    primary: '#0070f3',
  },
}

export default function App({ Component, pageProps }) {
  return (
    <>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        <Component {...pageProps} />
      </ThemeProvider>
    </>
  )
}

4: pages/_document.js,替换代码如下

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}
上一篇:React样式模块化解决方案--styled-components


下一篇:CSS-IN-JS 方案 - Emotion 库