Reactjs:带有reactjs的jQuery自定义内容滚动条

我试着在这里集成Jquery自定义滚动条插件。 这是我的代码

import $ from "jquery"; import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; ..... componentDidMount: function() { // fixed sidebar var self = this; mCustomScrollbar($); $(ReactDom.findDOMNode(this.refs.menu_fixed)).mCustomScrollbar({ autoHideScrollbar: true, theme: 'minimal', mouseWheel:{ preventDefault: true } }); self.forceUpdate(); }, 

我得到这个错误index.jsx:51 Uncaught TypeError:(0,_malihuCustomScrollbarPlugin2.default)不是函数

有人可以帮助让它工作谢谢

这不是React错误。 这是基于你的模块加载器(webpack,我猜?)将jQuery插件视为ES2015模块。 尝试以CommonJS样式导入插件。 换句话说,替换:

 import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; 

有:

 var mCustomScrollbar = require('malihu-custom-scrollbar-plugin'); 

如果这不起作用,您将需要共享有关模块加载器及其配置的更多信息。

也就是说,正如Toby所说,尝试将jQuery插件与React组件相结合通常是不可靠和棘手的,所以请谨慎行事。

这是我在我的反应项目中开展工作的解决方案。 我采用了最初的连接和缩小文件并创建了一个可导出的类,以便我的反应组件可以使用它。

这是我做的:

 // MCustomScrollBar.js export default class MCustomScrollbar { constructor() { /* MCustomScrollbar depends on jquery mousewheel. So I went to my browser url and typed http://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js I selected all the content on the page and pasted it into my constructor() here. */ /* I then copied all the contents of jquery.MCustomScrollbar.concat.min.js and pasted it into my constructor() here. */ } } 

太好了,现在我已准备好在我的反应组件中使用它。 这是我如何使用它的一个例子

 // MyHomeComponent.js import React from 'react'; import $ from 'jquery'; export default class MyHomeComponent extends React.Component { componentDidMount() { const MCSB = require('.//MCustomScrollBar'); let mcsb = new MCSB.default(); $("#mypage").mCustomScrollbar({theme:'dark'}); } render() { return (
Enter a lot of content here..
); } }

编辑

虽然我粘贴了缩小的代码,但您也可以粘贴原始代码。 如果您打算修改插件代码,那将更容易。