You need to enable JavaScript to run this app. React结合TypeScript:带children的组件props应使用什么类型?使用ReactElement报错
优惠活动
大模型
产品
解决方案
定价
更多

React结合TypeScript:带children的组件props应使用什么类型?使用ReactElement报错

报错根因

你当前的类型标注存在概念混淆:
ReactElement 是用于描述JSX渲染产物(比如<div />、<CustomComponent />这类元素)的TS类型,它的固定结构为{ type, props, key },完全不是React函数组件接收的入参属性集合的类型。
当你把props的类型标注为ReactElement时,TS会把传入的props识别为一个独立的ReactElement实例,自然无法在这个实例上找到children字段,最终抛出对应类型错误。

正确的类型标注方案

方案1:严格兼容Typography原生属性

透传第三方组件属性时,优先复用组件自带的全量类型,避免重复手写类型定义,同时保证类型完全匹配:

  1. 基于Typography的原生props定义扩展PageTitle的属性类型,明确声明children的类型:
import type { ComponentProps } from 'react';
// 继承Typography的所有原生属性,明确声明children类型
type PageTitleProps = ComponentProps<typeof Typography> & {
  children: React.ReactNode;
}
  1. 组件实现时解构拆分children和剩余透传属性,避免重复传参:
export default function PageTitle({ children, ...restProps }: PageTitleProps) {
  return (
    <Typography 
      variant='h3' 
      style={{ fontWeight: 600 }} 
      gutterBottom 
      {...restProps}
    >
      {children}
    </Typography>
  )
}

方案2:内置工具类型简化写法

如果需要快速为任意props结构补充children类型,可以直接使用React内置的PropsWithChildren工具类型做快捷声明:

import type { PropsWithChildren, ComponentProps } from 'react';

type PageTitleProps = PropsWithChildren<ComponentProps<typeof Typography>>;

export default function PageTitle({ children, ...restProps }: PageTitleProps) {
  return (
    <Typography variant='h3' style={{fontWeight: 600}} gutterBottom {...restProps}>
      {children}
    </Typography>
  )
}
常见踩坑提醒
  • 不要混用组件的返回值类型和入参类型:React函数组件的返回值类型才是ReactElement | null,入参永远是描述所有可接收属性的对象类型
  • 透传属性时,将自定义固定属性写在展开透传属性的前面,让外部传入的属性可以覆盖组件默认值,符合常规组件设计逻辑
  • 当需要把props透传给内部组件时,一定要把children从剩余透传属性中解构摘出,避免出现同一属性重复传递的冗余代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 05:36:00