HOW - React 组件中传递一个组件属性如何定义

在 React 中,如果你希望通过属性传递一个组件,通常有以下几种常见情况及对应的类型定义方法。


1. 传递一个 React 组件类型

如果你希望传递的是一个组件(例如 MyComponent 或类似的组件),可以用 React.ComponentType 定义类型。

tsx 复制代码
interface Props {
    Component: React.ComponentType<any>; // 接受任何组件
}

const Wrapper: React.FC<Props> = ({ Component }) => {
    return (
        <div>
            <Component />
        </div>
    );
};

// 用法
const MyComponent = () => <div>Hello</div>;

<Wrapper Component={MyComponent} />;
类型解释
  • React.ComponentType<any>: 表示一个可以渲染的 React 组件,可能是函数组件或类组件。
  • 如果你知道具体的组件需要的 props 类型,可以替换 any 为具体的 props 类型。

2. 传递一个 React 节点或组件实例

如果允许传递组件实例(例如 <MyComponent />)或普通的 React 节点,类型是 React.ReactNode。

tsx 复制代码
interface Props {
    children: React.ReactNode; // React 节点或组件实例
}

const Wrapper: React.FC<Props> = ({ children }) => {
    return <div>{children}</div>;
};

// 用法
<Wrapper>
    <div>Hello</div>
    <MyComponent />
</Wrapper>;
类型解释
  • React.ReactNode 表示任何可以被渲染的内容,包括:
    • JSX 元素
    • 字符串、数字、布尔值、null、undefined
    • 数组
    • React.Fragment 等

3. 传递一个渲染函数

如果你希望传递的是一个渲染函数(可以接收参数并返回一个组件),可以用 (props: Props) => JSX.Element 定义类型。

tsx 复制代码
interface Props {
    render: (data: string) => JSX.Element;
}

const Wrapper: React.FC<Props> = ({ render }) => {
    const data = "Hello, world!";
    return <div>{render(data)}</div>;
};

// 用法
<Wrapper render={(data) => <div>{data}</div>} />;
类型解释
  • (data: string) => JSX.Element 是一个函数类型,接受 data 参数并返回 JSX。

4. 动态组件(带 props 的组件)

如果传递的组件需要特定的 props,可以明确指定类型。

tsx 复制代码
interface ChildProps {
    message: string;
}

interface WrapperProps {
    Component: React.ComponentType<ChildProps>; // 组件需要 ChildProps 类型的 props
}

const Wrapper: React.FC<WrapperProps> = ({ Component }) => {
    return <Component message="Hello from Wrapper" />;
};

// 用法
const MyComponent: React.FC<ChildProps> = ({ message }) => <div>{message}</div>;

<Wrapper Component={MyComponent} />;

选择适合的类型

用途 类型定义
传递 React 组件类型 React.ComponentType
传递组件实例或子节点 React.ReactNode
传递渲染函数 (props: Props) => JSX.Element
传递带特定 props 的组件类型 React.ComponentType<Props>

根据实际需求选择合适的类型!

相关推荐
星栈5 小时前
我在浏览器里试了试 PhotoCraft|Rust + WASM 修图,是玩具还是生产力?
前端
雨中飘荡的记忆5 小时前
淘宝搜不到的东西,能不能去全世界找?一个程序员的创业尝试
前端·设计
kyriewen6 小时前
我让 4 位 AI 面试官打分,同一个我差了 40 分
前端·面试·程序员
htzyl2067 小时前
Vue3中watch的deep默认值:reactive与ref为什么相反
前端·vue.js
用户112936112197 小时前
没写样式为什么还找我要 wxss?uni-app 这个 ENOENT 坑多数人误判了
前端·微信小程序·uni-app
用户553665935267 小时前
从零做一个全国山峰与线路库:山野抽签的初衷、架构与踩坑
前端
夕水8 小时前
用 SolidJS 复刻 DeepSeek Chat —— 顺便把 ew-solid-ui 拷打了一遍
前端·javascript
qq_274475158 小时前
第 17 篇:ES6 语法速览:解构赋值、展开运算符、模板字符串、对象简写
前端·ecmascript·es6
2603_965896628 小时前
JavaScript 原型与原型链,读懂 JS 对象的底层机制
开发语言·javascript·原型模式
凯程序猿1号9 小时前
Web墨卡托EPSG3857瓦片行列号XYZ与经纬度双向换算及地面分辨率推导
前端·电脑