javascript - Nextjs 在使用 babel-plugin-styled-components 时抛出类名不匹配错误
问题描述
我已经从下一个样式组件示例中复制了 _document.js,并且我正在使用样式组件文档中的 babel 插件,但我仍然收到错误消息。
_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": [
[
"babel-plugin-styled-components"
]
]
}
星期三才开始使用 next ,所以该技术还是相当新的,但我已经查看了所有文档,这似乎是应该工作的,但我仍然收到错误,有什么想法吗?
解决方案
您没有在 render() 之后返回 () 任何 jsx。这很可能是您的问题。您还应该从“next/document”导入 Html、Head、Main 和 NextScript。
要解决您的问题,请尝试如下重构:
import Document { Html, Head, Main, NextScript } 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()
}
}
render() {
return (
<Html lang='en'>
<Head>
<meta charSet='utf-8' />
{this.props.styles}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
然后在 _app.jsx 中,您{ ThemeProvider }
将从 styled-components 导入。ThemeProvider 包装了从另一个文件导入的自定义样式组件GlobalTheme
JSX 元素。以下片段是我几个月前建立的一个项目的打字稿。大多数与 AppProps 花絮有关:
import Head from "next/head";
import { AppProps } from "next/app";
import { ThemeProvider } from "styled-components";
import { GlobalStyle, theme } from "../shared";
export default function App({ Component, pageProps }: AppProps) {
return (
<ThemeProvider theme={theme}>
<GlobalStyle theme={theme} />
<Head>
<title>Next.js</title>
</Head>
<main className="main">
<Component {...pageProps} />
</main>
</ThemeProvider>
)
}
推荐阅读
- java - 如何从 macOS Catalina build 10.15.4 运行 java?
- python - 如果返回null,如何结束循环?
- kubernetes - 使用 microk8s 连接到 redis
- python - 使用python可视化小波系数
- linux - 尝试将 C 代码与 Linux 上的 ICU Unicode 库链接时出现奇怪的问题
- python - 熊猫:如何删除熊猫数据框中所有列的主要缺失值?
- swiftui - .onAppear 中的崩溃画布 SwiftUI
- php - Symfony 文件上传不能在 Firefox 中工作,但在 Chrome 中
- angular - 当我尝试显示名称时值不起作用
- kubernetes - Airflow 无法识别我的 S3 连接设置