【问题标题】:How I can use my jquery plugin in Next.js?如何在 Next.js 中使用我的 jquery 插件?
【发布时间】:2020-01-20 13:55:15
【问题描述】:

我正在使用 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>
    );
  }
}

【问题讨论】:

    标签: import hyperlink jquery-plugins reload next.js


    【解决方案1】:

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

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

    【讨论】:

    • 您好,谢谢您的帮助,您能用示例代码解释更多细节吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2021-10-05
    • 2016-08-08
    • 2023-03-10
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多