如何在 Next.js 中使用我的 jquery 插件? [英] How I can use my jquery plugin in Next.js?

查看:43
本文介绍了如何在 Next.js 中使用我的 jquery 插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm developing web app using Next.js and I'd like to use jQuery in Next.js. But I can't import jquery plugin. please check my code and Help me.


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

推荐答案

如果你使用 jQuery,你会遇到的一个典型问题是,在导入 jQuery 插件后,它们会注册 onClick 事件,到那时你不能保证实际的 DOM 元素已准备好,元素可能会在以后创建并可能会被刷新.

One typical issue you will get into if you do jQuery is, After importing the jQuery plugins they will register for onClick events, and by that time you can't guarantee that the actual DOM Element is ready, elements may get created later and may get refreshed.

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

One way of solving the issues is call the jQuery code which does the initialization in componentDidMount() and also in componentDidUpdate() so that you can make sure the DOM elements are present before the jQuery plugin register them.

这篇关于如何在 Next.js 中使用我的 jquery 插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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