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

如何在Mock数据对象数组中获取两张图片并赋值给同数组内的第三个对象?

Hey,我帮你梳理下怎么解决这个问题,分为Mock数据构建和组件渲染两个部分来搞:

一、先搞定Mock对比数据的构建

你需要把前两个对象的image字段赋值给第三个对象的comparisons属性,这里有两种简单的实现方式:

方式1:提前创建前两个对象再直接引用

这种方式直观易懂,适合固定数量的对比图场景:

import faker from 'faker';
import uuid from 'uuid/v1';

// 先单独创建前两个上传对象
const firstCard = {
  avatar: faker.image.avatar(),
  description: faker.lorem.sentences(),
  id: uuid(),
  image: faker.image.avatar(),
};

const secondCard = {
  avatar: faker.image.avatar(),
  description: faker.lorem.sentences(),
  id: uuid(),
  image: faker.image.avatar(),
  name: faker.name.findName(),
};

// 构建完整的Mock数组,第三个对象直接引用前两个的image
const fakeUploads = [
  firstCard,
  secondCard,
  {
    avatar: faker.image.avatar(),
    // 这里用对象存储对比图,键对应索引
    comparisons: {
      0: firstCard.image,
      1: secondCard.image
    },
    description: faker.lorem.sentences(),
    id: uuid(),
    name: faker.name.findName(),
  },
];

方式2:动态处理数组(适合批量场景)

如果后续需要扩展更多对比图,可以用数组方法动态生成:

import faker from 'faker';
import uuid from 'uuid/v1';

// 先生成基础的3个卡片对象
const baseCards = Array.from({length: 3}, () => ({
  avatar: faker.image.avatar(),
  description: faker.lorem.sentences(),
  id: uuid(),
  image: faker.image.avatar(),
  name: faker.name.findName(),
}));

// 动态给第三个卡片添加对比图数据
const fakeUploads = baseCards.map((card, index) => {
  if (index === 2) {
    return {
      ...card,
      comparisons: {
        0: baseCards[0].image,
        1: baseCards[1].image
      }
    };
  }
  return card;
});

二、组件渲染逻辑调整优化

你原来的判断条件values.includes(comparisons)不太准确,应该直接检查当前卡片是否存在comparisons属性,同时加个容错避免图片加载出错:

// 先定义UPLOAD常量(比如:const UPLOAD = '上传图片';)

{/* 遍历fakeUploads时,每个元素为upload */}
{upload.comparisons && upload.comparisons[0] && upload.comparisons[1] ? (
  <span style={{ display: 'flex', gap: '8px' }}>
    <img width="50%" alt={UPLOAD} src={upload.comparisons[0]} />
    <img width="50%" alt={UPLOAD} src={upload.comparisons[1]} />
  </span>
) : (
  <img alt={UPLOAD} src={upload.image} />
)}

这里用flex布局让两张图片并列显示,gap可以控制图片间的间距,同时通过upload.comparisons[0] && upload.comparisons[1]确保对比图存在时才渲染对比布局,否则 fallback 到单图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:39:15