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

React Native自定义组件如何支持JSX嵌套方式传入子组件

解决方案

错误原因

React 组件的第一个入参永远是完整的 props 对象,你通过 JSX 嵌套传入的子元素会被自动挂载到 props 的 children 属性上,而非直接作为组件的入参。你之前将入参声明为 ReactElement 类型,和实际传入的 { children: Element } 类型不匹配,才会触发对应的 TypeScript 报错。

正确实现方式

方式1:显式声明Props类型(推荐)

使用 React 内置的 PropsWithChildren 工具类型,可以快速给你的 Props 加上 children 的类型定义:

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

// 若组件无其他自定义Props,直接用空对象即可
type CustomParentProps = PropsWithChildren<{}>

function CustomParentComponent(props: CustomParentProps): ReactElement {
  const { children } = props;
  // 此处可以加你的组件自定义逻辑,比如包裹样式、统一逻辑处理等
  return (
    <div className="custom-parent-wrapper">
      {/* 渲染嵌套传入的子元素 */}
      {children}
    </div>
  );
}

如果需要加其他自定义Props,直接在泛型参数里加即可:

type CustomParentProps = PropsWithChildren<{
  title: string;
  disabled?: boolean;
}>

方式2:使用React.FC类型快捷定义

React.FC 是 React 提供的函数式组件类型别名,默认已经内置了 children 的类型支持:

import type { FC, ReactElement } from 'react';

// 无自定义Props的写法
const CustomParentComponent: FC = (props): ReactElement => {
  const { children } = props;
  return <div>{children}</div>;
}

// 带自定义Props的写法
type CustomParentProps = {
  title: string;
}
const CustomParentComponent: FC<CustomParentProps> = (props): ReactElement => {
  const { children, title } = props;
  return (
    <div className="wrapper">
      <h2>{title}</h2>
      {children}
    </div>
  )
}

两种写法都可以实现你要的 JSX 嵌套传入子组件的效果,不会再触发类型报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:39:02