正如我从我的SO 问题中了解到的,我可以使用 next/head 在我的 React/Next JS 应用程序的组件中嵌入一个脚本标签。所以,我是这样处理的:
import React, { Component } from "react";
...
import Head from "next/head";
export const Lead = props => {
return (
...
<Head>
<script
class="3758abc"
type="text/javascript"
src="https://cdn2.fake.com/Scripts/embed-button.min.js"
data-encoded="1234sdkljfeiASD9A"
></script>
</Head>
...
);
};
不幸的是,没有任何渲染。我不知道我是否在这里遗漏了一些明显的东西......我正在使用 Next 9.1.7。
我的 _app.js 看起来像这样:
import App, { Container } from "next/app";
import Page from "../components/Page";
import { ApolloProvider } from "react-apollo";
import withData from "../lib/withData";
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
// this exposes the query to the user
pageProps.query = ctx.query;
return { pageProps };
}
render() {
const { Component, apollo, pageProps } = this.props;
return (
// <Container>
<ApolloProvider client={apollo}>
<Page>
<Component {...pageProps} />
</Page>
</ApolloProvider>
// </Container>
);
}
}
export default withData(MyApp);
我的 _document 看起来像这样:
import Document from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static getInitialProps = async 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();
}
};
}