How I can use my jquery plugin in Next.js?

泪湿孤枕 提交于 2021-01-21 10:33:09

问题


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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/58012570/how-i-can-use-my-jquery-plugin-in-next-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!