这里缺少的是服务器上的样式注入。基本上,当您在 JavaScript 中编写样式时,您必须在服务器上获取生成的样式并将它们作为style
标记注入到生成的 HTML 中。
Next 的内置解决方案会自动为您执行此操作,styled-components
您必须做一些手动工作并添加一个pages/_document.js
如下所示的文件:
import Document, { Head, Main, NextScript } from 'next/document'
import { styleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps ({ renderPage }) {
const page = renderPage()
const styles = (
<style dangerouslySetInnerHTML={{ __html: styleSheet.rules().map(rule => rule.cssText).join('\n') }} />
)
return { ...page, styles }
}
render () {
return (
<html>
<Head>
<title>My page</title>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
请注意我们如何使用来自 的样式注入样式标签styled-components
。这就是它的全部内容,现在那些没有样式的内容已经消失了!(这取自官方示例)
注意:使用v2styled-components
(即将推出,您现在可以使用 `npm i --save styled-components@next 获得它)将有一个用于 SSR 的官方 API,因此它看起来更像这样:
import Document, { Head, Main, NextScript } from 'next/document'
import styleSheet from 'styled-components/lib/models/StyleSheet'
export default class MyDocument extends Document {
static async getInitialProps ({ renderPage }) {
const page = renderPage()
const styles = (
<style dangerouslySetInnerHTML={{ __html: styleSheet.getCSS() }} />
)
return { ...page, styles }
}
render () {
return (
<html>
<Head>
<title>My page</title>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
希望有帮助!