gpt4 book ai didi

jquery - 将 jQuery 插件集成到 NextJS

转载 作者:行者123 更新时间:2023-12-04 16:40:50 25 4
gpt4 key购买 nike

我正在尝试集成一个已有六年历史的 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 is not a function

ReferenceError: the window is not defined // I'm getting this error because library use the windows in the last line

我还将向您展示我用来初始化元素的片段。

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

谢谢,对不起我的英语!

最佳答案

我创建了一个小型 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>
);
}

关于jquery - 将 jQuery 插件集成到 NextJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61029733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com