【问题标题】:Scroll to y location within react element with useRef使用 useRef 滚动到反应元素内的 y 位置
【发布时间】:2020-03-24 14:36:18
【问题描述】:

我的页面上有一个可以滚动的组件,但其余部分没有。当我使用不同的组件更改 useState 值时,我想滚动到此元素中的某个 Y 位置。

const scrollMe = useRef();  

useEffect(
        () => {
                if (scrollMe === true) {
                    scrollPanel.scrollTo(0, 300)
                }

        },
        [ scrollMe ]
    );

可滚动组件是这样的:

 <div ref={scrollMe} onScroll={(e) => handleScroll(e)}>A mapped array</div>

滚动功能如下:

const handleScroll = (e) => {
    if (e.target.scrollTop !== 0) {
        setTopBarPosition(true);
    } else {
        setTopBarPosition(false);
    }
};

设置topBarPosition会影响

<div className={`topBar ${topBarPosition === true ? 'topBarToTop' : ''}`}>
                    <TopBar/>
</div>

而css类topBarToTop将topBar移动到页面顶部:

.topBarToTop {
    top: 30px;
}

为什么我只是得到 scrollMe.scrollTo 不是一个函数?

我制作了一个代码框来说明我正在尝试做的事情:

https://codesandbox.io/s/react-hooks-counter-demo-izho9

【问题讨论】:

  • 能否请您发布整个组件或至少在您使用scrollMe 参考的地方?
  • 请创建一个codeandbox示例。更容易重现你的错误
  • 嗨,我做了一个 - 问题中的链接
  • @Davtho1983 嘿,请在这个codesandbox 上抢购一下这是你想要达到的目标吗?
  • 太棒了,谢谢!如果您将其发布为答案将接受:)

标签: reactjs scroll


【解决方案1】:

你需要做一些小改动,请按照代码cmets

  useEffect(() => {
    // swap the conditions to check for childRef first
    if (childRef && topPosition) {

      // use to get the size (width, height) of an element and its position
      // (x, y, top, left, right, bottom) relative to the viewport.
      const { y } = childRef.current.getBoundingClientRect()

      // You have to call `current` from the Ref
      // Add the `scrollTo()` second parameter (which is left)
      childRef.current.scrollTo(y, 0)

      // Initially it was set to `false` and we change it to `true` when click on scroll
      // button then we change it back to `false` when re-render 
      setTopPosition(false)

    }
  }, [topPosition, childRef])

更多关于getBoundingClientRect()

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2011-08-13
    • 2018-04-25
    • 2015-06-16
    相关资源
    最近更新 更多