React.js div scrollIntoView 不平滑

问题描述 投票:0回答:1

我有一个显示组件,本质上只是显示卡片列表。我有另一个组件,用于获取卡片并将其添加到

cards
状态,显示组件可以访问该状态来映射和渲染卡片。将卡片添加到
cards
后,显示屏底部有一个空的 div,我想将其滚动到视图中,以便用户无需滚动即可自动看到新卡片。我使用 ref 来获取 div 引用并使用
scrollIntoView({ behavior: 'smooth' })
方法,但它滚动不顺畅。我还尝试添加
html { scroll-behavior: smooth }
作为 CSS,但这也不能解决问题。

显示.tsx

const Display: React.FC = () => {
  const bottomDivRef = useRef<null | HTMLDivElement>(null)

  // currentSessionThreads is a list of ID associated with a card's information. State is stored using Redux
  const currentSessionThreads = useSelector((store: IRootState) => {
    const currentSession = store.ideator.value.currentSession
    if (currentSession === null) {
      return
    }
    return store.ideator.value.sessionsMap[currentSession].threads
  })
  const threadsMap = useSelector(
    (store: IRootState) => store.ideator.value.threadsMap
  )
  const ideasMap = useSelector(
    (store: IRootState) => store.ideator.value.ideasMap
  )

  // Everytime a new ID is added to currentSessionThreads, scroll the newest card into view.
  useEffect(() => {
    bottomDivRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [currentSessionThreads])

  return (
    <Box flex='1'>
      <VStack w='100%'>
        {currentSessionThreads?.map((threadID, index) => {
          return (
            <IdeaCard
              idea={ideasMap[threadsMap[threadID].idea]}
              ideaNumber={index + 1}
              key={index}
            />
          )
        })}
      </VStack>

      <Box w='100%' h='8rem' ref={bottomDivRef} />
    </Box>
  )
}

当我通过另一个更新包含 currentSessionThreads 的 redux 存储的组件添加新卡时,它不会平滑地滚动新内容。它只是跳到它那里。我不确定为什么这不起作用。

html css reactjs typescript
1个回答
0
投票

要解决 React 应用程序中

scrollIntoView({ behavior: 'smooth' })
滚动不顺畅的问题,请检查以下几点:

1。浏览器支持: 确保您的浏览器支持平滑滚动

scrollIntoView

2。 CSS 冲突: 检查是否有任何可能覆盖滚动的 CSS 行为。

3. React 渲染生命周期: 使用

setTimeout
中的
useEffect
来延迟
scrollIntoView
调用,为 DOM 提供更新时间 新卡。

useEffect(() => {
  setTimeout(() => {
    bottomDivRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, 100);
}, [currentSessionThreads]);

4。参考分配: 验证

ref
已正确分配并且 滚动时元素存在于 DOM 中。

5。组件重新渲染: 确保您的组件没有重新渲染 不必要的,这可能会中断平滑滚动。

6。容器属性: 检查容器元素的属性 (

Box
,
VStack
) 兼容平滑滚动。

7。可滚动祖先: 确认存在可滚动祖先

bottomDivRef
元素。

在不同的浏览器和环境中进行测试,以确定问题是否特定于某个浏览器和环境。如果问题仍然存在,请考虑其他方法,例如带有平滑滚动填充的

window.scrollTo

© www.soinside.com 2019 - 2024. All rights reserved.