ref scrollIntoView 不适用于反应上的平滑行为

Gar*_*end 8 reactjs js-scrollintoview react-ref react-usememo react-scroll

我正在创建一个组件,该组件将保存动态元素列表,出于样式原因,我需要将每个部分的标题保留在粘性导航菜单中。当用户上下滚动部分列表时,我需要应用样式规则,并将菜单导航中的同一部分带入视图,因此我尝试将scrollIntoView与菜单部分引用一起使用。

我的内部工作和逻辑似乎按预期工作,但是存在一个问题 - 除非我检查或在页面上使用刷新,否则scrollIntoView的函数不会在每次状态更改时执行

const scrollTo = (ref) => {
  ref.current.scrollIntoView({ behavior: "smooth", inline: "center" });
};
Run Code Online (Sandbox Code Playgroud)

为了简单起见,我已将我的工作添加到此codesandbox中

任何帮助将不胜感激,因为我已经没有想法了。

谢谢

编辑:

如果我从scrollIntoViewOptions选项中删除行为参数中的“smooth”选项,滚动行为似乎会按预期工作。然而它看起来确实很神经质。

const scrollToMenu = (ref) => {
  ref.current.scrollIntoView({ inline: "center", });
};
Run Code Online (Sandbox Code Playgroud)

Jth*_*rpe 5

奇怪的是,scrollIntoView()同步调用时不起作用,但就我而言,将其放入setImmediate()工作正常:

const scrollToMenu = (ref) => {
    setImmediate(() => ref.current.scrollIntoView({ inline: "center", }));
};
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,我不明白为什么这个有效,但它确实有效。 (2认同)