如何将Nextjs +样式化组件与Material-UI集成

Ale*_*rdi 11 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,并且在页面加载时不会闪烁。

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

提前致谢。

evg*_*tia 18

试试这个

_document.js

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

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

    try {
        ctx.renderPage = () => originalRenderPage({
            enhanceApp: App => props => styledComponentsSheet.collectStyles(materialSheets.collect(<App {...props} />))
          })
        const initialProps = await Document.getInitialProps(ctx)
        return {
          ...initialProps,
          styles: (
            <React.Fragment>
              {initialProps.styles}
              {materialSheets.getStyleElement()}
              {styledComponentsSheet.getStyleElement()}
            </React.Fragment>
          )
        }
      } finally {
        styledComponentsSheet.seal()
      }
  }

  render() {
    return (
      <html lang="en" dir="ltr">
        <Head>
          <meta charSet="utf-8" />
          {/* Use minimum-scale=1 to enable GPU rasterization */}
          <meta
            name="viewport"
            content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
          />
          {/* PWA primary color */}
          <meta
            name="theme-color"
            content={theme.palette.primary.main}
          />
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

export default MyDocument;
Run Code Online (Sandbox Code Playgroud)

.babelrc

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}
Run Code Online (Sandbox Code Playgroud)

有关更新,请检查https://github.com/MarchWorks/nextjs-with-material-ui-styled-components

  • @alevardi这是我创建的github存储库https://github.com/MarchWorks/nextjs-with-material-ui-styled-components (3认同)
  • 事实上,我错了,也许当 @MehmetN.Yarar 发现这个线程时它已经过时了,从现在开始购买我只是克隆了你的存储库来看看发生了什么,一切都工作得很好。非常感谢您所做的这项工作! (2认同)