css React.js div scrollIntoView不平滑

u5i3ibmn  于 4个月前  发布在  React
关注(0)|答案(1)|浏览(59)

我有一个显示组件,它基本上只是显示一个卡片列表。我有另一个组件,它获取一张卡片并将其添加到cards状态,显示组件可以访问该状态来Map和渲染卡片。在将卡片添加到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商店的组件添加新卡时,它不能平滑地滚动新内容。它只是跳转到它。我不知道为什么这不起作用。

ncecgwcz

ncecgwcz1#

要解决scrollIntoView({ behavior: 'smooth' })在React应用程序中滚动不流畅的问题,请检查以下几点:

**1.浏览器支持:**确保您的浏览器支持scrollIntoView平滑滚动。
**2. CSS冲突:**检查是否有CSS覆盖滚动行为。
**3. React Rendering插件:**在useEffect中使用setTimeout来延迟scrollIntoView调用,以便DOM有时间更新新卡。

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

字符串

**4. Ref赋值:**确认ref赋值正确,滚动时DOM中存在该元素。
**5.组件重渲染:**确保组件没有不必要的重渲染,否则会影响平滑滚动。
**6.容器属性:**检查容器元素(BoxVStack)的属性是否兼容平滑滚动。
**7.可滚动祖先:**确认bottomDivRef元素存在可滚动祖先。

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

相关问题