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

IT技术 javascript jquery reactjs
2021-05-03 14:02:37

IM试着整合jQuery的定制滚动条插件,这里的react。这是我的代码

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) is not a function

有人可以帮助使它工作吗谢谢

2个回答

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

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

和:

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

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

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

这是我的解决方案,可以让我的react项目中的事情发挥作用。我采用了原始的连接和缩小的文件,并制作了一个可导出的类,以便我的 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.
  */

  }


}

太好了,现在我已经准备好在我的 React 组件中使用它了。这是我如何使用它的示例

// MyHomeComponent.js
import React from 'react';
import $ from 'jquery';

export default class MyHomeComponent extends React.Component {
  componentDidMount() {
    const MCSB = require('./<path>/MCustomScrollBar');
    let mcsb = new MCSB.default();

    $("#mypage").mCustomScrollbar({theme:'dark'});

  }
  render() {
    return (<div id="mypage">Enter a lot of content here..</div>);
  }

}

编辑

尽管我粘贴了缩小后的代码,但您也可以粘贴原始代码。如果您打算修改插件代码,这会更容易。