多列轮播反应

Multiple column carousel react

我正在尝试在 React 中制作一个多列旋转木马(4 列),它可以响应地工作(在平板电脑或台式机上它仍然滚动 4)。当您单击箭头时,我希望它滑动 4,以便显示接下来的 4 个项目。 目前,我的 clickCount 没有及时更新,无法将 scrollTo 设置为正确的值。此外,我在调整屏幕大小时一直遇到问题(有时它会跳过某个项目或走得太远)。 顺便说一句,每个项目的宽度为 25%。

这是我目前所掌握的 -

const [clickCount, setClickCount] = useState(0)

const scrollSlide = (direction: 'next' | 'prev') => {
    const width = mainWrap.current?.clientWidth
    if (direction === 'next') {
        setClickCount(clickCount + 1)
        scrollTo = width * clickCount
    } else {
        setClickCount(prevState => prevState - 1)
        scrollTo = scrollTo - width
    }
    containerRef.current?.scrollTo({
        behaviour: 'smooth',
        left: scrollTo
    })
}

return (
    <div ref={mainWrap}>
        <button onClick={() => scrollSllides('prev')}>Prev</button>
        <button onClick={() => scrollSllides('next')}>Next</button>
        <div ref={containerRef}>
            {items?.map((item, index) => (
                <ItemComponent
                    key={index}
                    title={item.title}
                    image={item.image}
                />
            ))}
        </div>
    </div>
)

我刚刚根据您提供的代码定义了这个滑块:https://codesandbox.io/s/epic-feynman-jvt1q?file=/src/styles.css

const Slider = ({ items }) => {
  const [clickCount, setClickCount] = React.useState(0);
  const mainWrap = React.useRef();
  const containerRef = React.useRef();

  const scrollSllides = (direction) => {
    const width = mainWrap.current?.clientWidth;
    let scrollTo;

    const diff = direction === "next" ? 1 : -1;
    const newValue = (clickCount + diff) % (items.length / 4);
    setClickCount(newValue);
    scrollTo = width * newValue;

    containerRef.current?.scrollTo({
      behavior: "smooth",
      left: scrollTo
    });
  };

  return (
    <div ref={mainWrap}>
      <button onClick={() => scrollSllides("prev")}>Prev</button>
      <button onClick={() => scrollSllides("next")}>Next</button>
      <div className="Slider" ref={containerRef}>
        {items?.map((item, index) => (
          <ItemComponent key={index} title={item.title} image={item.image} />
        ))}
      </div>
    </div>
  );
};

与下一个CSS:

.Slider {
  width: 100%;
  height: 100px;
  overflow: scroll;
  white-space: nowrap;
}

.ItemComponent {
  display: inline-block;
  width: 25%;
  height: 100px;
}