【发布时间】:2020-12-03 21:13:15
【问题描述】:
我在尝试加载 Google 字体时遇到了以下问题。我读到我应该在_document.js 中写这样的东西来将它导入到头部标签中
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link
rel="preload"
href="/fonts/noto-sans-v9-latin-regular.woff2"
as="font"
crossOrigin=""
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
但这是我必须用来使 Styled Components 与 Next.js 一起使用的代码
import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
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();
}
}
}
所以我的问题是:如何修改我的 _document.js 文件以使用 Google 字体的样式?
另外,如果有任何帮助,这是我正在使用的 GlobalStyle,它不会导入字体
import { createGlobalStyle } from '@xstyled/styled-components';
const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css2?family=Lato&family=Rubik&display=swap');
* {
margin: 0;
padding: 0;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 62.5%;
position: relative;
background: grey;
}
body {
font-family: 'Lato', sans-serif;
}
`;
const BasicLayout = ({ children }: { children: any }) => {
return (
<>
<GlobalStyle />
{children}
</>
);
};
export default BasicLayout;
【问题讨论】:
-
请注意,您可以使用 npmjs.com/package/styled-reset-advanced 或 npmjs.com/package/styled-reset 在全局样式中注入 CSS 重置 ;)
标签: css reactjs next.js server-side-rendering styled-components