React 中如何修改按钮点击后颜色滑动切换的展示顺序?
实现方案
核心思路
- 预先定义固定顺序的颜色数组
['yellow', 'red', 'blue', 'green'],严格匹配需求的切换顺序 - 用
useState存储当前激活颜色的索引,初始值为0对应第一个黄色 - 点击按钮时更新索引:每次索引+1,取模数组长度实现循环切换
- 通过CSS的
transform配合transition属性实现平滑的滑动切换效果
完整可运行代码
组件代码
import { useState } from 'react'; import './ColorSlide.css'; const ColorSlideSwitch = () => { // 颜色顺序严格按照需求:黄、红、蓝、绿 const COLOR_SEQUENCE = ['yellow', 'red', 'blue', 'green']; const [currentIndex, setCurrentIndex] = useState(0); const handleSwitch = () => { setCurrentIndex(prev => (prev + 1) % COLOR_SEQUENCE.length); }; return ( <div className="color-slide-wrapper"> <div className="slide-view-port"> <div className="slide-track" style={{ transform: `translateX(-${currentIndex * 100}%)` }} > {COLOR_SEQUENCE.map((color, index) => ( <div key={index} className="color-panel" style={{ backgroundColor: color }} /> ))} </div> </div> <button onClick={handleSwitch} className="trigger-btn">点击切换</button> </div> ); }; export default ColorSlideSwitch;
对应CSS文件(ColorSlide.css)
.color-slide-wrapper { width: 320px; margin: 24px auto; } .slide-view-port { width: 100%; height: 180px; overflow: hidden; border-radius: 8px; margin-bottom: 16px; } .slide-track { display: flex; height: 100%; /* 滑动动画配置 */ transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1); } .color-panel { flex: 1 0 100%; height: 100%; } .trigger-btn { width: 100%; padding: 10px 0; border: none; border-radius: 6px; background: #2385bb; color: #fff; cursor: pointer; font-size: 14px; }
效果说明
点击按钮后,滑动轨道会按照计算的偏移量向左移动对应宽度,实现颜色按照黄→红→蓝→绿→黄的顺序循环平滑滑动切换,单次滑动动画耗时0.35s,可根据需求调整CSS中transition的时长参数。
内容的提问来源于stack exchange,提问作者user16590865
相关产品推荐
相关产品推荐

