您需要做一些小改动,请按照代码操作
评论
:
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()