如何将 Material UI v5 连接到 Next JS v12?

问题描述 投票:0回答:2

近日,Material UI 5 发布。以前(在 Material UI 4 中),我曾经通过修改

_document.js
_app.js
来连接它。 Material UI 5 也一样吗?

适用于 MUI v4

_app.js

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

class MyApp extends App {

   render() {
      const {Component, pageProps, router} = this.props;

      return (
          <ThemeProvider>
             <CssBaseline />
              <Component {...pageProps}/>
          </ThemeProvider>
      )
   }
}

export default MyApp

适用于 MUI v4

_document.js

import Document, {Html, Main, NextScript} from "next/document";
import { ServerStyleSheets } from '@material-ui/core/styles';

export default class MyDocument extends Document {
   static async getInitialProps(ctx) {
      const initialProps = await Document.getInitialProps(ctx);
      let props = {...initialProps};

      return props;
   }

   render() {
      return (
          <Html>
             <body>
             <Main/>
             <NextScript/>
             </body>
          </Html>
      );
   }
}


MyDocument.getInitialProps = async (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 is rendered after the app and register rendering finish.
      styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
   };
};

我想问的是:我是否应该以同样的方式连接到MUI v5?

也许有更优雅的方法来做到这一点?

reactjs material-ui next.js
2个回答
2
投票

它的连接方式仍然与我在问题中提供的相同,通过

_app.js
_document.js

的一些更改

使用 Next js 的官方 MUI 示例

https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs


0
投票

如果您只是从

@materail-ui/core/styles
导入 CSS,您可以直接在
_App.js
中导入 CSS...

import '@materail-ui/core/styles/someFilename.css'
(不需要
from
)并且应该可以从那里在您的应用程序中的任何位置访问它。

© www.soinside.com 2019 - 2024. All rights reserved.