在React中处理滚动动画

在React中处理滚动动画

本文介绍了在React中处理滚动动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React中处理滚动位置的正确方法是什么?因为更好的用户体验,我真的很喜欢平滑滚动。因为在React中操作DOM是一种反模式我遇到了问题:如何平滑地滚动到某个位置/元素?我通常会更改元素的scrollTop值,但这是对DOM的操作,这是不允许的。

What is the correct way of dealing with scroll position in React? I really like smooth scrolling because of better UX. Since manipulating the DOM in React is an anti-pattern I ran into problem: how to scroll smoothly to some position/element? I usually change scrollTop value of an element, but this is a manipulation on the DOM, which is not allowed.

代码:

import React from 'react';
import ReactDOM from 'react-dom';


class App extends React.Component {
  handleClick = e => {
    for (let i = 1; i <= 100; i++) {
      setTimeout(() => (this.node.scrollTop = i), i * 2);
    }
  };

  render() {
    const someArrayToMap = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    return (
      <div ref={node => this.node = node} style={{overflow: 'auto', height: '100vh'}}>
        <button onClick={this.handleClick}>CLICK TO SCROLL</button>
        {
            [...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap].map((e, i) => <div key={i}>some text here</div>)
        }
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById('root'));

如何以 React 的方式实现这一目标?

How to achieve this in a React way?

推荐答案

你可以使用refs和 scrollIntoView 方法(带行为:'流畅'用于平滑滚动)。它只有几行代码,不需要包。

You can just use refs and the scrollIntoView method (with behavior: 'smooth' for smooth scrolling). It's only a few lines of code and doesn't require a package.

说这就是你要滚动到的地方

Say this is what you want to scroll to

<p ref={this.myRef} className="scrollToHere">[1] ...</p>

还有某种按钮

<button onClick={() => {this.scroll(this.myRef)}} className="footnote">[1]</button>

调用滚动方式

to call the scroll method

class App extends Component {
  constructor() {
    super()
    this.myRef = React.createRef();

  scroll(ref) {
    ref.current.scrollIntoView({behavior: 'smooth'})
  }
}

编辑:因为所有浏览器尚不支持此方法(),您可能想要使用。

Because this method is not yet supported by all browsers (overview of browser support), you might want to use a polyfill.

这篇关于在React中处理滚动动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 17:35