Javascript 使用 Reactjs 获取滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53158796/
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 05:04:18  来源:igfitidea点击:

Get scroll position with Reactjs

javascriptreactjs

提问by Hai Tien

I use reactjs and want to handle scroll with clickevent.

我使用 reactjs 并希望处理带有click事件的滚动。

Firstly, I rendered list of posts with componentDidMount.

首先,我用componentDidMount.

Secondly, by click eventon each post in list, It will display post detail and scroll to top (because I put post detail to top position of page).

其次,click event在列表中的每个帖子上,它将显示帖子详细信息并滚动到顶部(因为我将帖子详细信息放在页面的顶部位置)。

Thirdly, by clicking "close button"in post detail, it will return previous list of posts but I want website will scroll to exactly to position of clicked post.

第三,通过点击"close button"帖子详细信息,它将返回以前的帖子列表,但我希望网站将滚动到点击帖子的确切位置。

I use like this:

我这样使用:

Click event to view post detail:

点击事件查看帖子详情:

inSingle = (post, e) => {
   this.setState({
        post: post,
        theposition: //How to get it here?
   });
   window.scrollTo(0, 0);
}

I want to get state of thepositionthen I can do scroll exactly to position of clicked post by 'Close event'.

我想获得状态theposition然后我可以完全滚动到点击帖子的位置'Close event'

采纳答案by sbr_amd

This should work:

这应该有效:

this.setState({
    post: post,
    theposition: window.pageYOffset
});

回答by EQuimper

You can use event listener in react like you will use in other js framework or library.

您可以在 React 中使用事件侦听器,就像在其他 js 框架或库中使用一样。

componentDidMount() {
  window.addEventListener('scroll', this.listenToScroll)
}

componentWillUnmount() {
  window.removeEventListener('scroll', this.listenToScroll)
}

listenToScroll = () => {
  const winScroll =
    document.body.scrollTop || document.documentElement.scrollTop

  const height =
    document.documentElement.scrollHeight -
    document.documentElement.clientHeight

  const scrolled = winScroll / height

  this.setState({
    theposition: scrolled,
  })
}

回答by Lucas Andrade

In case you need to keep on track of the scroll position, you can use react hooks to do so, that way it's possible to check the scroll position any time you need it:

如果您需要跟踪滚动位置,可以使用 react hooks 来做到这一点,这样就可以在需要时随时检查滚动位置:

import React, { useState, useEffect } from 'react';

...
// inside component:

const [scrollPosition, setSrollPosition] = useState(0);
const handleScroll = () => {
    const position = window.pageYOffset;
    setSrollPosition(position);
};

useEffect(() => {
    window.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
        window.removeEventListener('scroll', handleScroll);
    };
}, []);

In this case useEffectwill behavior similar to componentDidMount, it will fire once the component has rendered, but also in every render, as Jared Beach commented bellow: "window.addEventListener is smart enough to discard subsequent calls with the same parameters". . Make sure to return the cleanup function, similar to what you'd do in componentWillUnmount.

在这种情况下,useEffect行为类似于componentDidMount,它会在组件渲染后触发,但也会在每次渲染中触发,正如 Jared Beach 评论道:“window.addEventListener 足够聪明,可以丢弃具有相同参数的后续调用”。. 确保返回清理函数,类似于您在componentWillUnmount.

回答by Bhojendra Rauniyar

Like this:

像这样:

theposition: e.y // or, e.pageY

Or,

或者,

theposition: e.clientY - e.currentTarget.getBoundingClientRect().top

回答by Pavittar Singh

to get current scroll position you can use

获取您可以使用的当前滚动位置

horizontal scrolling amount window.pageXOffset

水平滚动量 window.pageXOffset

vertical scrolling amount window.pageYOffset

垂直滚动量 window.pageYOffset

回答by aitbella

this repo helped me a lot https://github.com/n8tb1t/use-scroll-position

这个 repo 帮了我很多 https://github.com/n8tb1t/use-scroll-position

yarn add @n8tb1t/use-scroll-position

import { useScrollPosition } from '@n8tb1t/use-scroll-position'


useScrollPosition(({ prevPos, currPos }) => {
 console.log(currPos.x)
 console.log(currPos.y)
})

回答by Bohdan Yashchuk

import React, { useLayoutEffect, useState } from 'react';

export default function useWindowPosition() {
  const [scrollPosition, setPosition] = useState(0);
  useLayoutEffect(() => {
    function updatePosition() {
      setPosition(window.pageYOffset);
    }
    window.addEventListener('scroll', updatePosition);
    updatePosition();
    return () => window.removeEventListener('scroll', updatePosition);
  }, []);
  return scrollPosition;
}