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

React数组映射传递图片props出现裂图无法展示不同图片如何解决

问题根因

你当前service.js中存储的image字段是普通字符串,和Services.js内导入的图片资源变量没有建立关联,所以直接传给<img>的src属性无法正常识别加载。

解决方案1(推荐:逻辑更清晰)

将图片导入操作直接放在service.js中,把image字段赋值为导入的图片资源对象,无需修改其他文件代码:

// service.js 修改后代码
import weightloss from '../assets/weightloss.jpg';
import weightgain from '../assets/weightgain.jpg';
import kids from '../assets/kids.jpg';

export const service = [
  {
    id: 1,
    name: 'WEIGHT LOSS',
    image: weightloss
  },
  {
    id: 2,
    name: 'WEIGHT GAIN',
    image: weightgain
  }, 
  {
    id: 3,
    name: 'KIDS CARE',
    image: kids
  }
]

解决方案2(无需修改service.js)

在Services.js中建立字符串与图片资源的映射表,根据传入的image字符串匹配对应资源:

// Services.js 修改后代码
import React from "react";
import "./services.css";
import weightloss from '../assets/weightloss.jpg';
import weightgain from '../assets/weightgain.jpg';
import kids from '../assets/kids.jpg';

// 建立映射关系
const imageMap = {
  weightloss,
  weightgain,
  kids
}

const Services = ({name, image}) => {
  return (
    <div className="services">
      <h3>{name}</h3>
      {/* 从映射表中读取对应图片,补充alt属性避免控制台警告 */}
      <img src={imageMap[image]} alt={name} />
    </div>
  );
} 
export default Services; 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:09:05