在 ReactJS 中,实现一排很长的卡片,每个卡片下方都有一个“下一个”按钮,点击按钮后卡片自动滑动到下一个内容,可以使用 React 的状态管理来实现。

首先,你需要在组件中定义一个状态来表示当前卡片的索引值。可以使用 useState 钩子函数来创建状态:

import React, { useState } from 'react';

function CardList() {
  const [currentIndex, setCurrentIndex] = useState(0);

  // 其他代码...

  return (
    <div>
      {/* 卡片列表 */}
      <div className="card-list">
        {/* 渲染卡片列表 */}
      </div>

      {/* 下一个按钮 */}
      <button onClick={() => setCurrentIndex(currentIndex + 1)}>
        下一个
      </button>
    </div>
  );
}

然后,在卡片列表的渲染部分,你可以使用 currentIndex 来控制当前展示的卡片。可以通过样式来实现卡片的滑动效果,比如设置 transform: translateX() 来改变卡片的位置:

import React, { useState } from 'react';

function CardList() {
  const [currentIndex, setCurrentIndex] = useState(0);

  const cardList = [...]; // 卡片列表数据

  // 点击下一个按钮时,切换到下一个卡片
  const handleNextCard = () => {
    setCurrentIndex(currentIndex + 1);
  };

  return (
    <div>
      {/* 卡片列表 */}
      <div className="card-list" style={{ transform: `translateX(-${currentIndex * 100}%)` }}>
        {/* 渲染卡片列表 */}
        {cardList.map((card, index) => (
          <div key={index} className="card">
            {/* 卡片内容 */}
          </div>
        ))}
      </div>

      {/* 下一个按钮 */}
      <button onClick={handleNextCard}>
        下一个
      </button>
    </div>
  );
}

在上面的代码中,currentIndex * 100 用来计算卡片列表的偏移量,实现卡片的滑动效果。你可以根据实际情况调整偏移量的计算方式。

通过以上代码,当点击下一个按钮时,卡片列表会根据当前索引值自动滑动到下一个卡片的位置。

ReactJS 实现卡片自动滑动:点击“下一个”按钮切换卡片

原文地址: https://www.cveoy.top/t/topic/pTTj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录