【问题标题】:NextJs - Where can we add a <script> code?NextJs - 我们可以在哪里添加 <script> 代码?
【发布时间】:2021-07-15 07:08:54
【问题描述】:

在 NextJs 应用程序中,我想添加 &lt;script&gt; 代码但没有找到添加的位置以及如何添加?我尝试将其添加到 .js 文件中,但无法识别。

在 react 中,我们有 index.html 来添加这些东西,那么在 Nextjs 应用中呢?

【问题讨论】:

标签: javascript html reactjs next.js


【解决方案1】:

要编辑index.html,NextJS 中的等价物是_document.js file

自定义文档通常用于扩充应用程序的 &lt;html&gt;&lt;body&gt; 标记。

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
          <script>...</script>
        </body>
      </Html>
    )
  }
}

如果您只想将元素附加到&lt;head&gt; 标记(针对特定页面),请使用next/head

import Head from 'next/head'

function IndexPage() {
  return (
    <>
      <Head>
        <script>....</script>
      </Head>
    </>
  )
}

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2023-03-10
    • 2021-12-17
    相关资源
    最近更新 更多