使用useRef在React元素中滚动到指定位置

3
我页面上有一个可滚动的组件,但其他部分却不滚动。当我使用不同的组件更改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 is not a function" 的错误信息?

我制作了一个codesandbox来说明我正在尝试做什么:

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


1
请问您能否发布整个组件或至少使用scrollMe引用的位置? - norbitrial
1
请创建一个 CodeSandbox 示例。这样更容易重现您的错误。 - Fiodorov Andrei
嗨,我在问题中放了一个链接。 - Davtho1983
1
@Davtho1983 你好,请看一下这个codesandbox。这是你想要实现的吗? - awran5
哦,我明白了。const newY = y + 100; childRef.current.scrollTo(0, newY); - Davtho1983
显示剩余3条评论
1个回答

3

您需要进行一些小的更改,请按照代码注释进行:

  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() 的内容


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接