代码之家  ›  专栏  ›  技术社区  ›  Davtho1983

滚动到带有useRef的react元素中的y位置

  •  0
  • Davtho1983  · 技术社区  · 6 年前

    我的页面上有一个可以滚动的组件,但其余的没有。当我使用不同的组件更改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);
        }
    };
    

    <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

    0 回复  |  直到 6 年前
        1
  •  1
  •   awran5    6 年前

    您需要做一些小改动,请按照代码操作 评论 :

      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()

    推荐文章