You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React健身应用中身体部位组件图片无法动态切换问题求助

问题:React健身应用身体部位卡片图片无法对应展示

开发React健身应用时,身体部位列表的每张卡片需显示对应部位的图片,但当前所有卡片显示同一张图片。API返回的身体部位数据已正确渲染为独立卡片,仅图片匹配失败。

问题原因

查看BodyPart.js代码,图片路径使用了状态值bodyPart而非当前卡片的item值:

const image = require(`../assets/images/bodypart/${bodyPart}.jpg`);

bodyPart是当前选中的部位状态,因此所有卡片都会渲染选中部位的图片,而非各自对应的身体部位图片。

解决方案

将图片路径中的bodyPart替换为当前卡片的item值,确保每张卡片加载对应部位的图片:

修改后的BodyPart.js代码:

import React from 'react'
import { Stack, Typography } from '@mui/material';

const BodyPart = ({ item, setBodyPart, bodyPart}) => {
    // 使用item作为图片文件名,匹配当前卡片的身体部位
    const image = require(`../assets/images/bodypart/${item}.jpg`);
   
    return (
        <Stack type="button"
            alignItems="center"
            justifyContent="center"
            className="bodyPart-card"
            sx={{
                borderTop: bodyPart === item ? '4px solid #ff2625' : '',
                backgroundColor: "#fff",
                borderBottomLeftRadius: '20px',
                width: '270px',
                height: '280px ',
                cursor: 'pointer',
                gap: '47px'
            }}
            onClick={()=>{
                setBodyPart(item);
                window.scrollTo({top:1800, left:100, behavior:'smooth'})
            }}
        >
            <img
                src={image}
                alt={item}
                style={{ width: '70px', height: '70px' }}
            />
            <Typography fontSize="24px" fontWeight="bold" color="#3A1212">
                {item}
            </Typography>
        </Stack>
    )
}

export default BodyPart

额外优化建议

如果API返回的部位名称和图片文件名存在格式差异(比如大小写、空格),可以用映射对象统一管理:

// 定义部位与图片路径的映射
const bodyPartImageMap = {
  'all': '../assets/images/bodypart/all.jpg',
  'chest': '../assets/images/bodypart/chest.jpg',
  'back': '../assets/images/bodypart/back.jpg',
  // 补充其他部位的映射关系
};

// 在组件中使用
const image = bodyPartImageMap[item];

这种方式能避免文件名与API返回值不匹配的问题,也更易于维护。

内容的提问来源于stack exchange,提问作者Gauri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:48:08