首页 > 解决方案 > 在 React 应用程序中初始化 PerfectScrollbar

问题描述

perfect-scrollbar我在我的应用程序中使用的是旧版本React。在旧版本中,ps.initialize()我使用了一种方法,ref用于我想使用完美滚动条的部分。

我尝试了新方法——见下文——但完美的滚动条似乎没有初始化。

import PerfectScrollbar from 'perfect-scrollbar';

class MyComponent extends Component {

   componentDidMount() {

      const sb1 = new PerfectScrollbar(this.refs.ref1);
      const sb2 = new PerfectScrollbar(this.refs.ref2);
      sb1.update();
      sb2.update();
   }

   render() {
      return(
           <div ref="ref1">
                Section 1
           </div>
           <div ref="ref2">
                Section 2
           </div>
      );
   }
}

export default MyComponent;

在应用程序中使用完美滚动条的正确方法是React什么?顺便说一句,有一个完美滚动条的React Wrapper,但它已经有一段时间没有更新了,这个新更新的版本perfect-scrollbar已经解决了旧版本的一些问题,所以我真的很想使用这个。我会很感激这里的一些指示。谢谢。

标签: javascriptreactjsperfect-scrollbar

解决方案


基本上阅读文档可以看到以下内容:

初始化:

const ps = new PerfectScrollbar('#container');

因此,您可以将代码更改为以下内容:

import PerfectScrollbar from 'perfect-scrollbar';

class MyComponent extends Component {

   componentDidMount() {

      const parent = new PerfectScrollbar('.parent');
      const sb1 = new PerfectScrollbar('.sb1');
      const sb2 = new PerfectScrollbar('.sb2');

      parent.update();
      sb1.update();
      sb2.update();
   }

   render() {
      return(
           <div className="parent">
                <div className="sb1" ref="ref1">
                     Section 1
                </div>
                <div className="sb2" ref="ref2">
                     Section 2
                </div>
           </div>
      );
   }
}

export default MyComponent;

使用您提到的包装器也很容易,这种包装器的想法是激活那些初始化。

你的代码最终会是这样的:

import PerfectScrollbar from 'react-perfect-scrollbar'

class MyComponent extends Component {

   render() {
      return(
           <PerfectScrollbar>
                <div className="sb1" ref="ref1">
                     Section 1
                </div>
                <div className="sb2" ref="ref2">
                     Section 2
                </div>
           </PerfectScrollbar>
      );
   }
}

export default MyComponent;

注意:您并没有说您使用的是什么版本,所以我只是假设您使用的是最新版本:)


推荐阅读