当前位置: 首页 > 工具软件 > Jedi-js > 使用案例 >

在next.js中使用styled-component的几种方案

阎知
2023-12-01

babel 配置可参考在next.js中使用styled-component以及全局主题切换
本文仅涉及覆盖_document.js结构

官网案例

with-styled-components

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()
        }
    }
}

添加默认结构

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

const resetStyles = `
html,body {
    height: 100%;
    font-family: "ruyi","Arial Rounded MT Bold", "Helvetica Rounded", Arial, sans-serif;
  }
`;

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()
        }
    }
    
	render () {
	   return( 
		   <Html>
				 <Head>
			         <link rel="stylesheet" type="text/css" href="/dmvendor.css" />
			          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css" />
			
			          <style dangerouslySetInnerHTML={{ __html: resetStyles }} />
		        </Head>
		     <body>
		        <Main />
		        <NextScript />
		      </body>
		    </Html>
	    )
	  }
}

styled-components文档

参考styled-components文档的实现方式更简洁
主要在getInitialProps处处理服务端

import Document, { Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'


const resetStyles = `
html,body {
    height: 100%;
    font-family: "ruyi","Arial Rounded MT Bold", "Helvetica Rounded", Arial, sans-serif;
  }
  @font-face {
    font-family: "ruyi";
    src: url(/font/metaVo.ttf) format("TrueType");
}
`;

class MyDocument extends Document {
    // styled-components 文档的支持ssr的书写方式
    static async getInitialProps({ renderPage }) {
        const sheet = new ServerStyleSheet();
        const page = await renderPage((Component) => (props) => sheet.collectStyles(<Component {...props} />));
        const styleElements = sheet.getStyleElement();
        return { ...page, styleElements };
    }
   
    render() {
        const { styleElements } = this.props;

        return (
            <Html>
                <Head>
                    <style dangerouslySetInnerHTML={{ __html: resetStyles }} />
                    {styleElements}
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        )
    }
}

export default MyDocument

NEXT要求返回参数包含一个 html,body,styles属性的对象

 类似资料: