Javascript 在 React 中处理滚动动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44375093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:29:02  来源:igfitidea点击:

Handling scroll Animation in React

javascriptreactjsredux

提问by sympi

What is the correctway 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.

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

JSBIN

JSBIN

code:

代码:

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'));

How to achieve this in a Reactway?

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

回答by bbrinx

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

您可以只使用 refs 和scrollIntoView方法(behavior: 'smooth'用于平滑滚动)。它只有几行代码,不需要包。

Say this is what you want to scroll to

说这是你想要滚动到的

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

And some sort of button

还有某种按钮

<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'})
  }
}

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

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

回答by transang

window.scroll({top: 0, left: 0, behavior: 'smooth' })works for me.

window.scroll({top: 0, left: 0, behavior: 'smooth' })为我工作。

You also need to check for browser's compability

您还需要检查浏览器的兼容性

Or use polyfill

或者使用polyfill



Edit: For the completeness sake, here is how to dynamically polyfill with webpack.

编辑:为了完整起见,这里是如何使用 webpack 动态填充。

if (!('scrollBehavior' in document.documentElement.style)) {
//safari does not support smooth scroll
  (async () => {
    const {default: smoothScroll} = await import(
      /* webpackChunkName: 'polyfill-modern' */
      'smoothscroll-polyfill'
      )
    smoothScroll.polyfill()
  })()
}

By this dynamic polyfill, the package is loaded via ajax unless the browser supports smooth scroll.

通过这个动态 polyfill,除非浏览器支持平滑滚动,否则包通过 ajax 加载。

polyfill-modernis an arbitrary chunk name, which hints webpack compiler to combine packages together, in order to reduce number of server requests.

polyfill-modern是一个任意的块名称,它提示 webpack 编译器将包组合在一起,以减少服务器请求的数量。

回答by Ranjan Rahi

The Simplest way to do: -

最简单的方法: -

window.scrollTo({top: 0, left: 0, behavior: 'smooth' });

This simple JavaScript code is working with all browser.

这个简单的 JavaScript 代码适用于所有浏览器。

回答by gabergg

There are several libraries for scrolling to anchors in React. The one to choose depend on the features you're seeking and the existing setup of your page.

在 React 中有几个用于滚动到锚点的库。选择哪个取决于您正在寻找的功能和页面的现有设置。

React Scrollable Anchoris a lightweight library that's specifically for scrolling to anchors that are mapped to URL hashes. It also updates the URL hash based on currently focused section. [Full disclosure: I'm the author of this library]

React Scrollable Anchor是一个轻量级库,专门用于滚动到映射到 URL 哈希的锚点。它还根据当前关注的部分更新 URL 哈希。[完全披露:我是这个库的作者]

React Scroll, mentioned in another answer, is a more fully featured library for scrolling to anchors, without any reflection of location in the URL.

在另一个答案中提到的 React Scroll 是一个功能更齐全的库,用于滚动到锚点,而不会对 URL 中的位置进行任何反映。

You can also hook up something like React Router Hash Link Scrollif you're already using React Router, which will then also tie into your URL hash.

如果你已经在使用 React Router,你也可以连接类似React Router Hash Link Scroll 的东西,然后它也会绑定到你的 URL 哈希中。

回答by PaulCo

I really enjoy the react-router websitein the API section, they seem to use this scrollToDoc componentthat is a really sweet translation of a typical VanillaJS smooth-scroll function into React which depends on react-motion!

我真的很喜欢API 部分中的react-router 网站,他们似乎使用了这个scrollToDoc 组件,这是将典型的 VanillaJS 平滑滚动功能转换为依赖于react-motion!

回答by Chase DeAnda

A couple good packages out there already that can handle this for you:

已经有几个很好的软件包可以为您处理这个问题:

https://github.com/fisshy/react-scroll- Demo

https://github.com/fisshy/react-scroll-演示

https://www.npmjs.com/package/react-scroll-to-componentSimple scroll to component

https://www.npmjs.com/package/react-scroll-to-component简单滚动到组件

Hope this helps!

希望这可以帮助!