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

React组件仅在prop定义时渲染元素及TypeError报错如何解决

错误原因与修复方案

错误根源

你当前定义的是React函数式组件,函数组件没有类组件的this实例对象,因此访问this.props时会抛出Cannot read property 'props' of undefined错误。

同时你已经在组件的入参位置完成了icon属性的解构赋值,不需要通过this.props再重复获取对应属性。

修复后的代码

export const Button = ({ children, link, icon, background }) => {
  return (
    <Link href={`${link}`} passHref>
      <button
        className={`mt-4 inline-flex px-5 py-3 rounded-xl text-base font-medium text-white ${background} hover:bg-indigo-800 active:bg-grey-900 focus:outline-none border-4 border-white focus:border-purple-200 transition-all`}
      >
        {children}
        {/* 直接使用解构出来的icon变量判断,不需要this.props */}
        {icon ? <Icon path={icon} /> : null}
      </button>
    </Link>
  );
};

写法优化建议

  • 条件渲染可以简化为更简洁的短路写法:{icon && <Icon path={icon} />},和原三元判断逻辑完全等价
  • 入参icon本身就是字符串类型,不需要用${icon}模板字符串再包裹转换,直接传入path属性即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:06:03