簡體   English   中英

React.js:使用React.js的jQuery自定義內容滾動條

[英]Reactjs: jQuery custom content scroller with reactjs

我試着在這里集成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組件結合起來通常是不可靠和棘手的,因此請謹慎行事。

這是我使我的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>);
  }

}

編輯

盡管我粘貼了縮小的代碼,但是您也可以粘貼原始代碼。 如果您打算修改插件代碼,那將使它更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM