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

React JSX组件无法接收参数,可复用卡片标签自定义问题求助

解决React卡片组件的参数传递问题

问题1:修改Project组件的props名报错

你给Project传递props用的是{...feature},而feature(即projects数组里的每一项)的属性是links,所以Project组件必须解构对应名字的props才能拿到值。如果想改成别的名字(比如tags),得在传递的时候重命名props,不能只改组件里的解构名:

// Projects组件里修改传递方式
<Project key={feature.id} tags={feature.links} index={index} />

// 然后Project组件里解构新的名字
const Project = ({tags}) => (
  // ... 其他代码不变,把原来的links换成tags
  {tags.map((item, index) => (
    <Feat key={item.name} {...item} index={index} />
  ))}
)

直接改解构名的话,props里没有对应键,会拿到undefined,调用map自然就报错了。

问题2:Feat组件展开传递值报错

你给Feat组件传递的是{...feature}(这里的feature是links数组里的每一项,结构是{name: 'xxx', link: 'xxx'}),但Feat组件里解构的是{feature}——两者不匹配,Feat根本拿不到feature这个props,渲染#{feature}时会显示#undefined或者报错。

有两种修复方式:

方式1:修改Feat组件的解构逻辑

既然传递的是name和link,直接解构需要的属性:

const Feat = ({name}) => (
  <div>
    <span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">#{name}</span>
  </div>
)

方式2:传递时把整个对象作为feature属性

如果想保持Feat组件的feature参数,传递时要明确传这个属性:

// Project组件里修改Feat的调用
<Feat key={feature.name} feature={feature.name} index={index} />
// 或者需要整个对象的话,传feature={feature},再在Feat里用feature.name

完整修正后的代码示例

import React from 'react'
import { projects } from "../constants";
import { star } from "../assets";

// 方式1的Feat组件
const Feat = ({name}) => (
    <div>
        <span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">#{name}</span>
    </div>
)

// 修改了props名为tags的Project组件
const Project = ({tags}) => (
    <div className="rounded overflow-hidden shadow-lg">
        <img className="w-full" src={star} alt="Mountain"/> {/* 原w-.1是笔误,改为w-full正常显示图片 */}
        <div className="px-6 py-4">
            <div className="font-bold text-xl mb-2">Mountain</div>
            <p className="text-gray-700 text-base">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus quia, Nonea! Maiores et perferendis eaque, exercitationem praesentium nihil.
            </p>
        </div>
        <div className="px-6 pt-4 pb-2">
            {tags.map((item, index) => (
                <Feat key={item.name} {...item} index={index} />
            ))}
        </div>
    </div>
)

const Projects = () => (
    <div className="p-10 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 gap-5">
        {projects.map((feature, index) => (
            <Project key={feature.id} tags={feature.links} index={index} />
        ))}
    </div>
)

export default Projects

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:55:22