首页 > 解决方案 > 在 reactjs 中使用分页创建组图像滑块

问题描述

我正在尝试创建一个带有分页的水平组图像滑块(类似于 react native 中的平面列表),但我在过去 2 天努力做到这一点。

我想做的和这个类似 在此处输入图像描述

我能够轻松创建 html/css,但问题是实现滑块的逻辑

我试图添加的功能:

  1. 5 个图像设置为活动图像,如果用户显示给用户

  2. 单击左侧按钮 ==> 前 5 个图像显示而不是活动图像

  3. 如果用户单击右键 ==> 显示下 5 个图像而不是活动图像

  4. 用户单击按钮时应更新分页(重要:每个索引代表一组图像......分页中的5个图像=> 1个索引)

我试图解决这个问题的方式:

1- 使用 createRef 为每个图像容器创建 ref

  useEffect(() => {
    const refsArray = [];

    data.forEach((item, index) => {
      //console.log(index);
      const newRef = createRef();

      refsArray.push(newRef);
    });

    setRefs(refsArray);
  }, []);

2- 使用这种方法将主阵列分成 3 个不同的部分(上一个,下一个活动):

setPrevItems(refs.slice(startIndex - count, startIndex));
setActiveItems(refs.slice(startIndex, startIndex + count));
setNextItems(refs.slice(startIndex + count, startIndex + count + count));

3-逻辑添加到按钮

  //left button handler

  const handleLeftClick = () => {
    
    //trying to hide the elments

    activeItems.forEach((item, index) => {
      item.current.style.left = `2000px`;
    });
    
   //trying to display previous items ... and using index to make them consecutive
    prevItems.forEach((item, index) => {
      item.current.style.left = `${300 * index}px`;
    });
   }


      //right button handler

      const handleRightClick = () => {
        activeItems.forEach((item, index) => {
          item.current.style.left = `-2000px`;
        });
    
        nextItems.forEach((item, index) => {
          item.current.style.left = `${300 * index}px`;
        });
       }

附加节点:我在同一个项目中创建了一个轮播......我这样做没有问题,但是具体实现这个功能并不顺利。

感谢您提前提供任何建议:)

标签: javascriptreactjsreact-nativecarousel

解决方案


查看react-slideshow-image 是一个幻灯片组件,React.js 支持滑动、淡出和缩放。您需要的大部分内容都可以通过此处描述的属性和方法来完成

const properties = {
autoPlay:false,
arrows: true,
}
/*SlideBanner represens each of your sectoins containing 5 images*/
const SlideBanner = (
    <div style={{flexDirection:'row'}}>
        <div className="imageContainer">
            <img src="your img number 1"/>
        </div>
        <div className="imageContainer">
            <img src="your img number 2"/>
        </div>
        ...
        <div className="imageContainer">
            <img src="your img number 5"/>
        </div>
     
    </div>
)

<Slide {...properties}>
    
   <SlideBanner/>
   <SlideBanner/>
   <SlideBanner/>
</Slide>

推荐阅读