css 如何在React中使用ref scrollLeft平滑地水平滚动

x4shl7ld  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(114)

我正在React中编写一个水平滑块,并希望onClick使用useRefscrollLeft滑动,它可以工作,但我似乎无法像scrollTo行为那样制作平滑的动画。
这是我的工作函数:

const scrollX = (direction = 'right') => {
    if (sliderRef.current) {
      const { clientWidth } = sliderRef.current

      direction === 'right'
        ? (sliderRef.current.scrollLeft += clientWidth)
        : (sliderRef.current.scrollLeft -= clientWidth)
    }
  }

期权就没有存在的

behavior: 'smooth'

我尝试在CSS中添加

scroll-behavior: smooth;

也不管用
有可能吗?或者我需要使用其他方法吗?
我在stackOverflow上找不到任何关于scrollLeft的东西,希望有人能帮上忙。
多谢了!

csbfibhn

csbfibhn1#

您可以使用scrollTo()来垂直、水平或同时进行滚动:

const { clientWidth, scrollLeft } = sliderRef.current

element.scrollTo({
  left: scrollLeft + clientWidth,
  behavior: "smooth",
});

相关问题