在react/next中滚动溢出组件

Blu*_*ret 5 javascript css reactjs next.js tailwind-css

所以我有一个具有固定宽度和overflow-x-auto的组件。我决定隐藏滚动条并将其替换为左右两个箭头/按钮。如果我单击左侧,它会向左滚动,反之亦然。我怎样才能实现这个功能?

这是我的组件

<div className={` vertical-card w-7/12 flex flex-row overflow-x-scroll no-scrollbar pb-4`}>
            {
                dataConselor.map((item, index) => {
                    return <VerticalCard key={item.id} name={item.nama} specialist={item.specialist} shortdesc={item.shortdesc} img={item.img} />
                })
            }

        </div>
Run Code Online (Sandbox Code Playgroud)

noi*_*mur 4

  1. 定位可滚动元素(您可以使用useRef,因为它是react):
const scrollable = useRef(null);

<div id="myElement" ref={scrollable}>
...
</div>
Run Code Online (Sandbox Code Playgroud)
  1. 创建滚动功能:
const scrollIt = (toRight) => {
  const scrollLength = ... //Calculate your scroll length however you want.
  scrollable.current.scrollBy({left: scrollLength * (toRight ? 1 : -1), behavior: "smooth"});
}
Run Code Online (Sandbox Code Playgroud)
  1. 将此功能添加到左/右按钮:
<div id="toLeft" onClick={()=>scrollIt(false)}>...</div>
<div id="toRight" onClick={()=>scrollIt(true)}>...</div>
Run Code Online (Sandbox Code Playgroud)