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 元素
    • 字符串、数字、布尔值、nullundefined
    • 数组
    • 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>

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

相关推荐
10mAh2 分钟前
【Linux】error while loading shared libraries 怎么解决?——ldd、RPATH 与动态链接排错
java·linux·前端
深念Y7 分钟前
stable-diffusion.cpp 的 FLUX.2 Klein 9B 分步
java·前端·数据库
小帅不太帅11 分钟前
1.5M 参数的 OCR 模型,我把它跑进了浏览器
前端·javascript·ai编程
风骏时光牛马20 分钟前
AI编程场景下故障根因分析与复盘总结
前端
Sterting40 分钟前
Element-Plus 入门与整体布局
前端·vue.js·elementui
程序员黑豆8 小时前
Java 注释详解:单行、多行与文档注释的完整指南
java·前端·ai编程
剪刀石头布啊8 小时前
antd中可编辑表格中巧用useWatch实现联动高性能效果,以及定制延伸学习
前端
油丶酸萝卜别吃9 小时前
前端转全栈学习路线
前端·学习
浮生望9 小时前
前端路由进阶:History API原理与手写HistoryRouter
前端
陆枫Larry9 小时前
JavaScript 中的竞态是什么,为啥会有竟态?
前端