Shadcn Component:ScrollArea
2 min read
目录

修改元组件

修改组件 ScrollAreaPrimitive.Root 的 ref 引用到 ScrollAreaPrimitive.Viewport 上。

const ScrollArea = React.forwardRef<
  React.ElementRef<typeof ScrollAreaPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
  <ScrollAreaPrimitive.Root
    className={cn("relative overflow-hidden", className)}
    {...props}
  >
    <ScrollAreaPrimitive.Viewport
      className="h-full w-full rounded-[inherit]"
      ref={ref} // +
    >
      {children}
    </ScrollAreaPrimitive.Viewport>
    <ScrollBar />
    <ScrollAreaPrimitive.Corner />
  </ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName

案例

  const scroller = useRef<HTMLDivElement>(null)
  // ... ...

  useEffect(() => {
    if (addressesResponse) {
      //NOTE - 数据变更时
      if (scroller.current) {
        scroller.current.scrollTop =
          scroller.current.scrollHeight - scroller.current.clientHeight * 1
      }
    }
  }, [addressesResponse])

  //NOTE - 搜索的时候应该重置缓存的列表数据,同时滚动位置重置
  useEffect(() => {
    if (debouncedQuery?.trim()) {
      if (scroller.current) {
        scroller.current.scrollTop = 0
      }
    }
  }, [debouncedQuery])

效果