如何使用Next/Head渲染脚本 [英] How to use Next/Head to render a script

查看:443
本文介绍了如何使用Next/Head渲染脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我从

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

很遗憾,没有任何显示.我不知道我是否在这里遗漏了一些明显的东西... 我正在使用Next 9.1.7.

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

我的_app.js看起来像这样:

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

我的_document看起来像这样:

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

推荐答案

在您的_document.js中,尝试在<NextScript />标签下面添加脚本

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>

这篇关于如何使用Next/Head渲染脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆