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

如何在TypeScript的JSX中正确映射对象数组并传递组件Props?

解决TypeScript下React组件Props类型不匹配问题

你的代码无法运行的核心原因是子组件的Props类型未正确定义,TypeScript无法识别父组件传递的name、description、tech、index这些属性。以下是修复步骤:

1. 定义项目数据的类型

在@/data文件中,先给单个项目对象定义类型,再约束整个数组的类型:

// @/data.ts
export type Project = {
  name: string;
  description: string;
  tech: string[];
};

export const Project1: Project[] = [ 
    {
        name: 'Interior Design Website',
        description: 'Responsive and minimalistic',
        tech:[
            'imgurl.com',
            'img2url.com',
            'img3url.com',
        ]
    },
    {
        name: 'Exterior Design Website',
        description: 'Responsive and minimalistic',
        tech:[
            'imgurl.com',
            'img2url.com',
            'img3url.com',
        ]
    },
    {
        name: 'Furniture Design Website',
        description: 'Responsive and minimalistic',
        tech:[
            'imgurl.com',
            'img2url.com',
            'img3url.com',
        ]
    }
]

2. 修正子组件的Props类型

子组件需要接收index和项目的所有属性,直接复用上面定义的Project类型来组合Props:

// ProjectArticle.tsx
import type { Project } from '@/data';

type Props = Project & {
  index: number;
};

export default function ProjectArticle({ index, name, description, tech }: Props) {
  return (
    <div>
      <h3>{index + 1}. {name}</h3>
      <p>{description}</p>
      <div>
        {tech.map((url, idx) => (
          <img key={idx} src={url} alt={`Tech icon ${idx + 1}`} />
        ))}
      </div>
    </div>
  );
}

3. 父组件补充key属性(可选但推荐)

父组件逻辑无需调整,建议给列表项加上key属性以符合React渲染规范:

import { Project1 } from '@/data';
import ProjectArticle from './ProjectArticle';

export default function ParentComponent() {
  return (
    <div>
      {Project1.map((project, index) => (
        <ProjectArticle
          key={index}
          index={index}
          {...project}
        />
      ))}
    </div>
  );
}

额外提示

  • 如果项目数据有唯一标识(比如id字段),优先用唯一标识作为key,比index更稳定。
  • 复用类型定义可以减少重复代码,同时保证数据结构的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:35:23