反应scrollIntoView()不适用于ref

时间:2020-10-31 18:30:15

标签: reactjs react-hooks react-ref js-scrollintoview

我的反应功能成分定义为

    export const NavMenuHorizontal: React.FunctionComponent<NavMenuProps> = (
      props
    ) => {         
        const selectedItemRef = React.createRef<HTMLDivElement>();
        React.useEffect(() => {
          selectedItemRef.current?.scrollIntoView({
            behavior: "smooth",
            inline: "center",
          })
        });

        return (
              <List>
              {map(...) => (
                  <div ref={isActive ? selectedItemRef : undefined}>
                     some text 
                  </div>
               )}
              </List>
        );
    };
//isActive is true for only one item in the map

我正在尝试使用ref使选定的列表项滚动到视图中,但无法获得预期的结果。但是,如果我尝试在钩子上添加调试断点,则它会按预期工作并在视口中滚动元素。

我还尝试将scrollIntoView包裹在setTimeout()内,该方法可以正常工作,但它会多次滚动并导致震颤效果。

0 个答案:

没有答案