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

标签 javascript html reactjs next.js

在 NextJs 应用程序中,我想添加 <script>代码,但没有得到在哪里添加以及如何添加?我尝试将其添加到 .js文件,但无法识别。
在 react 中,我们有 index.html要添加这些东西,在 Nextjs 应用程序中呢?

最佳答案

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

A custom Document is commonly used to augment your application's <html> and <body> tags.

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

关于javascript - NextJs - 我们可以在哪里添加 &lt;script&gt; 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67189907/

相关文章:

javascript - 哪个 MEAN 生成器 - javascript

javascript - Uncaught Error : SECURITY_ERR: DOM Exception 18 when I try to set a cookie

javascript - Prop 仅在我刷新页面后呈现

reactjs - YARN START在我的PC上失败,但在我的同事的PC上失败

javascript - 在 Mechanical Turk 中播放音频的按钮

javascript - 使用剑道创建一个单选按钮自定义(更改背景颜色)

javascript - AWS dynamodb 使用 "on-demand"ProvisionedThroughput 创建表

javascript - ng-click 不适用于我的任何 div

php - 无法使用 jquery mobile 在新选项卡中打开链接

javascript - html 输入类型文件接受图像不允许在 ios 11 中选择文件