热门搜索关键词怎么实现自动轮播切换?

西西的笔记 阅读 12

我在做搜索页的“热门搜索”模块,想让前10个关键词每隔3秒自动轮播展示,比如一次显示5个,然后平滑切换到下一组。试过用 setInterval 配合数组 slice 切片,但切换时没有过渡动画,而且最后一组不足5个时会出错。

现在数据是存在 state 里的:const hotKeywords = ['前端', 'React', 'Vue', 'CSS', 'JavaScript', 'TypeScript', 'Node.js', 'Webpack'],有没有比较优雅的实现方式?

下面是我写的切换逻辑,感觉太生硬了:

const [currentIndex, setCurrentIndex] = useState(0);
const itemsPerPage = 5;

useEffect(() => {
  const timer = setInterval(() => {
    setCurrentIndex(prev => (prev + 1) % Math.ceil(hotKeywords.length / itemsPerPage));
  }, 3000);
  return () => clearInterval(timer);
}, []);
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
迷人的国凤
优化一下你的代码,首先用CSS来处理动画过渡问题,这样切换时会更流畅。对于最后一组不足5个的情况,可以在展示前进行数据填充。

先定义样式让列表平滑过渡:

.keywords {
transition: all 0.5s ease;
}


然后在JSX里这样写:

const fillData = (data, length) => {
const filled = [...data];
while (filled.length < length) {
filled.push('');
}
return filled;
};

const HotKeywords = () => {
const [currentIndex, setCurrentIndex] = useState(0);
const itemsPerPage = 5;

useEffect(() => {
const timer = setInterval(() => {
setCurrentIndex(prev => (prev + 1) % Math.ceil(hotKeywords.length / itemsPerPage));
}, 3000);
return () => clearInterval(timer);
}, []);

const displayedKeywords = fillData(
hotKeywords.slice(currentIndex * itemsPerPage, (currentIndex + 1) * itemsPerPage),
itemsPerPage
);

return (

{displayedKeywords.map((keyword, index) => (
{keyword}
))}

);
};


这样做的话,过渡效果有了,最后一组不足的也处理好了,效率还挺高的。记得把样式类名加到外层div上。这比之前的实现要顺手多了,也不容易出错。
点赞
2026-03-27 21:00