<style global jsx />似乎没有被应用

时间:2019-07-25 15:42:21

标签: reactjs styles jsx next.js

我有一个自定义_document文件,内容如下所述。出于某些原因,<style global jsx />中指定的样式似乎未应用于首次渲染。在开发中,当我刷新页面时会应用它们,但是当我为静态导出构建站点时,即使刷新后也不会应用它们。

import { ServerStyleSheets } from '@material-ui/styles';
import Document, { Head, Main, NextScript } from 'next/document';
import React, { Fragment } from 'react';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: App => props => sheets.collect(<App {...props} />)
      });

    const initialProps = await Document.getInitialProps(ctx);

    return {
      ...initialProps,
      styles: (
        <Fragment>
          {initialProps.styles}
          {sheets.getStyleElement()}
        </Fragment>
      )
    };
  }

  render() {
    return (
      <html lang="en">
        <Head>
          <link
            href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,600,700&display=swap"
            rel="stylesheet"
          />

          <style global jsx>{`
            html {
              font-size: 16px;
            }

            a {
              text-decoration: none;
            }

            #__next {
              position: relative;
              display: flex;
            }

            #__next-prerender-indicator {
              display: none;
            }
          `}</style>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

export default MyDocument;

1 个答案:

答案 0 :(得分:1)

您应该将全局样式添加到_app中。至于为什么它在_document中不起作用,请检查此https://github.com/zeit/styled-jsx#server-side-rendering

我不确定是否可以,但是您可以这样做

import Document, { Html, Head, Main, NextScript } from 'next/document';
import flush from 'styled-jsx/server';

class MyDocument extends Document {
  static async getInitialProps (ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    initialProps.styles = flush()
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head>
          <link
            href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,600,700&display=swap"
            rel="stylesheet"
          />

          <style global jsx>{`
            html {
              font-size: 16px;
            }

            a {
              text-decoration: none;
            }

            #__next {
              position: relative;
              display: flex;
            }

            #__next-prerender-indicator {
              display: none;
            }
          `}</style>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}


export default MyDocument;