Next.js实现点击按钮循环切换头像图片的问题求助
import { useState } from 'react' import styles from '../styles/ProfileShowcase.module.scss' import Image from 'next/image' import GameLog from '../pages/Logs.js' import useUser from '../lib/useUser'; // 导入所有头像资源 import one from '/public/img/avatars/mask_avatars_one.png' import two from '/public/img/avatars/mask_avatars_two.png' import three from '/public/img/avatars/mask_avatars_three.png' import four from '/public/img/avatars/mask_avatars_four.png' import five from '/public/img/avatars/mask_avatars_five.png' import six from '/public/img/avatars/mask_avatars_six.png' // 头像数组提到组件外部,避免每次渲染重复创建 const avatars = [one, two, three, four, five, six] const ProfileShowcase = () => { // 用state存储当前展示的头像索引,默认展示第一张 const [currentAvatarIndex, setCurrentAvatarIndex] = useState(0) const profileLoop = () => { // 顺序循环逻辑:索引+1,到末尾自动回到0 setCurrentAvatarIndex(prev => { const nextIndex = prev + 1 return nextIndex >= avatars.length ? 0 : nextIndex }) // 如果需要随机切换而非顺序循环,替换为下面的逻辑即可 // setCurrentAvatarIndex(Math.floor(Math.random() * avatars.length)) } return ( <> <div className={styles.top_container}> <div className={styles.img_wrap}> {/* 取当前索引对应的头像资源,补全alt属性符合可访问性要求 */} <Image src={avatars[currentAvatarIndex]} alt="用户头像" /> <button className={styles.btn_update} onClick={profileLoop}>update profile picture</button> </div> </div> {/* <div className={styles.bottom_container}> <GameLog /> </div> */} </> ) } export default ProfileShowcase
调整说明
- 引入
useState钩子存储当前头像的索引,修改状态会触发组件重新渲染,自动更新展示的图片 - 头像数组直接存储导入的图片资源,不需要额外包裹对象,简化取值逻辑,放到组件外避免每次渲染重复创建
- 点击事件默认实现顺序循环逻辑,也保留了随机切换的可选方案
- 补全了Image组件的alt属性,符合可访问性规范,Next.js对本地导入的图片会自动识别宽高,无需额外配置
内容的提问来源于stack exchange,提问作者ZaneGilfillan
相关产品推荐
相关产品推荐

