如何将Nextjs +样式化的组件与material-ui集成

时间:2019-03-11 20:00:40

标签: material-ui styled-components next.js

1。。要使用样式化的组件构建next.js应用程序,确实非常容易。您只需要使用其_document.js片段即可启用SSR并防止页面加载时样式闪烁:https://github.com/zeit/next.js/blob/canary/examples/with-styled-components/pages/_document.js

2。。使用material-ui来构建next.js应用几乎是简单的。您只需要从另一个项目基础:https://github.com/mui-org/material-ui/tree/master/examples/nextjs开始,它就在_document.jshttps://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_document.js

上有自己的实现。

3。可悲的是,我无法弄清楚如何“合并”这两种实现并获得下一个应用程序,其中样式化组件和Material-ui组件可以共存,SSR且不会闪烁页面加载。

你能帮我吗? 互联网上是否有能力比我更好的人已经解决了这个问题,但我不知道?

先谢谢了。

3 个答案:

答案 0 :(得分:2)

这是我的_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();
      }
    }
  }

并在下面找到我的.babelrc文件:

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

答案 1 :(得分:0)

此解决方案在服务器端效果很好,对于客户端,您还需要更改注入顺序,如此处记录:https://material-ui.com/customization/css-in-js/#css-injection-order

要与next.js配合使用,您需要像这样更改jss常量的赋值:

const jss = create({
  ...jssPreset(),
  insertionPoint: process.browser
    ? window.document.getElementById('jss-insertion-point')
    : null
})

答案 2 :(得分:0)

对于上面代码仍然有问题的每个人:我还必须在 pages/_app.tsx 中包含 StylesProvider。

_app.tsx:

import { StylesProvider } from '@material-ui/core/styles';

<StylesProvider injectFirst>
  {/* Your component tree.
      Now, you can override Material-UI's styles. */}
</StylesProvider>

_document.tsx:

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

class MyDocument extends Document {
  render() {
    return (
      <html lang="en">
        <Head>
          <meta charSet="utf-8" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          <meta name="theme-color" content="#000000" />
          {/* Fonts and icons */}
          <link
            rel="stylesheet"
            type="text/css"
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons"
          />
          <link
            href="https://use.fontawesome.com/releases/v5.0.10/css/all.css"
            rel="stylesheet"
          />
        </Head>
        <body>
          <div id="page-transition" />
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {

  // Render app and page and get the context of the page with collected side effects.
  const materialSheet = new ServerStyleSheets();
  const styledComponentSheet = new ServerStyleSheet();
  const originalRenderPage = ctx.renderPage;

  try {
    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App) => (props) =>
          styledComponentSheet.collectStyles(
            materialSheet.collect(<App {...props} />),
          ),
      });

    const initialProps = await Document.getInitialProps(ctx);

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [
        ...React.Children.toArray(initialProps.styles),
        materialSheet.getStyleElement(),
        styledComponentSheet.getStyleElement(),
      ],
    };
  } finally {
    styledComponentSheet.seal();
  }
};

export default MyDocument;