码迷,mamicode.com
首页 > Web开发 > 详细

二)NextJS集成Styled Components

时间:2021-04-24 13:42:55      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ini   color   glob   creat   title   com   als   sync   log   

打开前一篇中建立的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()
    }
  }
}

二)NextJS集成Styled Components

标签:ini   color   glob   creat   title   com   als   sync   log   

原文地址:https://www.cnblogs.com/Andy1982/p/14695814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!