NextJs-我们可以在哪里添加<script>代码?

在 NextJs 应用程序中,我想添加<script>代码但不知道在哪里添加以及如何添加?我尝试将它添加到.js文件中,但没有识别。

index.htmlReact 中,我们必须添加这些东西,那么在 Nextjs 应用程序中呢?

回答

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

自定义文档通常用于扩充您的应用程序<html><body>标签。

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

如果您只想将元素附加到<head>标签(对于特定页面),请使用next/head

import Head from 'next/head'

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


以上是NextJs-我们可以在哪里添加&lt;script&gt;代码?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>