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

如何在ReactJS 18类组件中访问props.children?

React 18 类组件中修复 this.props.children 失效问题

你的代码里this.props.children在React 18中失效的核心原因是类组件的泛型props类型定义缺失了children属性,而非React 18废弃了类组件的children用法。

最小改动的修复方案

只需要修改组件的泛型参数,为props类型添加children定义即可,无需改动render方法里的return this.props.children代码。

方案1:手动添加children属性

直接在第一个泛型参数(props类型)中加入children?: React.ReactNode:

export class SystemStatusContainer extends React.Component<
  { children?: React.ReactNode }, // 这里添加children类型
  {
    status: systemStatuses;
    pollStatus: boolean;
  }
> {
  // ... 原有代码不变
  render() {
    const { status } = this.state;

    if (status === systemStatuses.offline) {
      return <SystemUnavailableModal />;
    } else if (status === systemStatuses.update) {
      return <SystemStatusModal />;
    } else {
      return this.props.children; // 这行完全不用改
    }
  }
}

方案2:使用React内置工具类型(更简洁)

用React.PropsWithChildren包裹原有的空props类型,自动添加children属性:

export class SystemStatusContainer extends React.Component<
  React.PropsWithChildren<{}>, // 用PropsWithChildren包裹空对象
  {
    status: systemStatuses;
    pollStatus: boolean;
  }
> {
  // ... 原有代码不变
  render() {
    // ... 原有render代码不变
  }
}

这两种方案都只修改了泛型定义部分,完全符合你“尽可能减少改动”的要求,修改后this.props.children就能正常在React 18中使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 00:32:13