且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在React中处理滚动动画

更新时间:2022-01-11 04:19:30

你可以使用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'})
  }
}

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

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