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

问题描述 投票:0回答:1

我以这种方式有一个滚动视图:一系列视图水平包裹在容器上。

      <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。目前,行为是我需要拖动水平滑动条,但如果我在视图上尝试相同,则无效。

javascript reactjs scrollbar
1个回答
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>
      );
    }
 }
© www.soinside.com 2019 - 2024. All rights reserved.