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

React HOC无法传递props?组件渲染为空求助

问题分析

你的代码存在两个核心问题:

  1. 语法错误:withLoading.jsx里的return <Component>{props.description}</Component>语句后多了一个多余的);,会导致代码无法正常运行。
  2. Button组件未使用传入内容:Button.jsx中的组件既没有接收props,也没有渲染传入的子元素,所以即使HOC传递了内容,按钮也不会显示任何文本。
修复方案

第一步:修正HOC的语法错误

修改withLoading.jsx,移除多余的括号:

export default function withLoading(Component) {
  const WithLoadingComponent = (props) => {
    return <Component>{props.description}</Component>;
  };

  return WithLoadingComponent;
}

第二步:让Button组件渲染传入的内容

有两种实现方式可选:

方式一:通过子元素渲染

修改Button.jsx,接收并渲染子元素:

import React from 'react'
import withLoading from './withLoading'

function Button({ children }) {
    return <button>{children}</button>
}
export default withLoading(Button)

方式二:直接接收description props

如果希望Button直接使用description props,可以调整HOC传递全部props,同时让Button接收该属性:

  • 修改withLoading.jsx:
export default function withLoading(Component) {
  const WithLoadingComponent = (props) => {
    return <Component {...props} />;
  };

  return WithLoadingComponent;
}
  • 修改Button.jsx:
import React from 'react'
import withLoading from './withLoading'

function Button({ description }) {
    return <button>{description}</button>
}
export default withLoading(Button)

验证效果

两种方式都能让<Button description="button"></Button>渲染出显示“button”的按钮,可根据实际需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:01:10