我如何在 Next.js 中使用我的 jquery 插件?

Xin*_*Lee 3 import jquery-plugins hyperlink reload next.js

我正在使用 Next.js 开发 Web 应用程序,我想在 Next.js 中使用 jQuery。但我无法导入 jquery 插件。请检查我的代码并帮助我。


import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage(App => props => sheet.collectStyles(<App {...props} />));
    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }

  render() {
    return (
      <html lang="en">
        <Head>{this.props.styleTags}
          <link
            href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css"
            rel="stylesheet"
          />
         <script src="../static/js/jquery.main.js" async/>
        </Head>
        <body>
          <Main />
          <div id="modal" />
          <NextScript />
        </body>
      </html>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

kar*_*ivi 6

如果你使用 jQuery,你会遇到的一个典型问题是,在导入 jQuery 插件后,它们将注册 onClick 事件,到那时你不能保证实际的 DOM 元素已准备好,元素可能会在稍后创建并且可能会得到神清气爽。

解决问题的一种方法是调用 jQuery 代码,该代码在 incomponentDidMount()和 in中进行初始化,componentDidUpdate()以便您可以确保在 jQuery 插件注册它们之前存在 DOM 元素。