Reactjs:如何访问scrollbox的属性(水平偏移)

时间:2018-03-06 15:53:22

标签: javascript reactjs scrollbar

我有这样一种滚动视图:水平包裹在容器上的一系列视图。

      <div id="scroller"  ref="scroller" onClick=
{this.onClick.bind(this)} onMouseMove={this._onMouseMove.bind(this)}>
                {this.state.pma.map((Item, index) => (
                  <this.state.typePma
                    key           = {index}
                    pma           = {Item}
                    onDateChange  = {(child)  => this.onDateChange(child)}
                    redisplay     = {()       => this.redisplay()}
                    />
                  ))}
              </div>

我想知道如何获得scrollview的水平偏移并以编程方式操作它:我想用鼠标简单地拖动我的scrollview。目前,我的行为是我需要拖动水平滑动条,但如果我在视图上尝试相同的操作则不起作用。

1 个答案:

答案 0 :(得分:1)

我真的不确定你在寻找什么,但如果你正在寻找一种方法来控制应用程序中延迟加载的滚动行为,那么例如,如果用户到达你想要的滚动的底部加载更多数据,你可以这样做。

class ScrollablePage extends Component {

  componentDidMount() {
    // Add Scroll Event After The UI Has Been rendered
    window.addEventListener("scroll", this.onHandleScrollEvent);
  }

  onHandleScrollEvent = () => {   
    const el = document.body;
    /*
     * el.scrollTop => This tells us how much a user has scrolled from up
     * Math.ceil(el.scrollTop) => returns value in whole rather then float
     */

    // this will start paginating when there is a difference of 100px from bottom
    const bottomSpace = 100; 
    const bottomReachLimit = Math.ceil(el.scrollTop) + (bottomSpace); 
    if (el.scrollHeight - el.clientHeight <= bottomReachLimit) {
        // console.log('Bottom reached, starting pagination');
        // Do your magic here when reached bottom
    } else { 
       // console.log('Bottom not reached');
    }
  }

  render () {
     return (
       <div>
         {/* YOUR SCROLLABLE CONTENT HERE */}
       </div>
     );
  }

}

但是如果你想通过代码控制Scroll行为,你可以做这样的事情。下面编写的代码将滚动到componentDidMount()页面的底部,但是这可以让您了解如何以命令方式控制滚动行为。

 import React, { Component } from 'react';
 import { findDOMNode } from "react-dom";

 class ScrollablePage extends Component {
    componentDidUpdate() {
      this.scrollToBottom();
    }

    scrollToBottom() {
       const el = findDOMNode(this)
       const scrollHeight = el.scrollHeight;
       const totalContainerHeight = el.clientHeight;
       const shouldScroll = scrollHeight - totalContainerHeight;

       const myInterval = setInterval(() => {
         if (shouldScroll > 0) {
           el.scrollTop = el.scrollTop + 70;
           if (el.scrollTop + el.clientHeight >= el.scrollHeight - 30) {
             clearInterval(myInterval);
           }
         }
       }, 20);
    }

    render () {
      return (
        <div>
           {/* YOUR SCROLLABLE CONTENT HERE */}
        </div>
      );
    }
 }