【问题标题】:Integrating a jQuery plugin into NextJS将 jQuery 插件集成到 NextJS
【发布时间】:2020-07-16 16:14:06
【问题描述】:

我正在尝试集成一个已有六年历史的 jQuery 插件,但我不能。

我尝试使用 react-dom 中的 findDOMNode 模块,甚至使用 React Official Docs 的方式来集成一个 jQuery 插件,但都没有。

这是我的插件 --> https://www.jqueryscript.net/layout/Fancy-Responsive-jQuery-Diamond-Layout-Plugin-diamonds-js.html

我遇到了一些错误,例如

TypeError: jquery__WEBPACK_IMPORTED_MODULE_8___default(...)(...).Diamonds 不是函数

ReferenceError: the window is not defined // 我收到此错误是因为库使用了最后一行中的窗口

我还向你展示了我用来初始化元素的 sn-p。

componentDidMount() {
  //   $(".diamondswrap").diamonds({
  //     size : 200, // Size of diamonds in pixels. Both width and height. 
  //     gap : 5, // Pixels between each square.
  //     hideIncompleteRow : false, // Hide last row if there are not enough items to fill it completely.
  //     autoRedraw : true, // Auto redraw diamonds when it detects resizing.
  //     itemSelector : ".item" // the css selector to use to select diamonds-items.
  // });

  if(typeof window !== 'undefined') {
    window.Diamonds = require('../assets/js/jquery.diamonds.js');
  }
  new Diamonds.Diamonds();
  }

谢谢,对不起我的英语!

【问题讨论】:

    标签: jquery reactjs next.js


    【解决方案1】:

    我创建了一个小型 Github 存储库,您可以在其中查看:https://github.com/tudorgergely/jquery-plugin-nextjs/

    这是工作演示:https://jquery-plugin-nextjs.now.sh/

    基本上你需要一些东西,首先使用不带ssr的动态组件渲染jquery-diamonds:

    const DynamicJqueryDiamonds = dynamic(
        () => import('../components/JqueryDiamonds'),
        { loading: () => <p>...</p>, ssr: false }
    );
    

    然后在该组件内部加载 jquery/diamonds in componentDidMount/useEffect:

        useEffect(() => {
            window.jQuery = require('../public/jquery-latest.min');
            window.Diamonds = require('../public/jquery.diamonds.js');
    
            window.jQuery("#demo").diamonds({
                size : 100, // Size of diamonds in pixels. Both width and height.
                gap : 5, // Pixels between each square.
                hideIncompleteRow : false, // Hide last row if there are not enough items to fill it completely.
                autoRedraw : true, // Auto redraw diamonds when it detects resizing.
                itemSelector : `.${styles.item}` // the css selector to use to select diamonds-items.
            });
        }, []);
    

    最后一件事,别忘了在 pages/index.js 中包含你的 CSS:

    例如:

    export default function Index() {
        return (
            <div>
                <Head>
                    <title>Test</title>
                    <link href="/diamonds.css" rel="stylesheet" key="test"/>
                </Head>
                <DynamicJqueryDiamonds/>
            </div>
        );
    }
    
    

    【讨论】:

    • 对于使用类组件的人,只需在 componentDidMount 函数中添加相同的代码,即在 useEffect 主体中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    相关资源
    最近更新 更多