How to use Next/Head to render a script

笑着哭i 提交于 2020-04-16 02:40:08

问题


As I understand from my SO question , I can use next/head to embed a script tag within a component of my React / Next JS app. So, I went about it as such:

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>
...
  );
};

Unfortunately, nothing rendered. I don't know if I'm missing something obvious here... I'm using Next 9.1.7.

My _app.js looks like this:


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);

And my _document looks like this:


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();
    }
  };
}


回答1:


in your _document.js, try to add script below <NextScript /> tag

<body>
   <Main />
   <NextScript />
   <script
        class="3758abc"
        type="text/javascript"
        src="https://cdn2.fake.com/Scripts/embed-button.min.js"
        data-encoded="1234sdkljfeiASD9A"></script>
</body>


来源:https://stackoverflow.com/questions/60919281/how-to-use-next-head-to-render-a-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!