ReactNode 和 CSSProperties 类似,它也是 React 提供的 TypeScript 类型定义(Type Definition),不是 JavaScript 类,也不是 TypeScript 内置类型。
它的主要作用是:
表示一个 React 组件可以渲染的内容类型。
1. 基本用法
import { ReactNode } from 'react';
interface Props {
children: ReactNode;
}
function MyComponent({ children }: Props) {
return (
<div className="container">
{children}
</div>
);
}
这里:
children: ReactNode;
表示 children 可以接收 React 支持渲染的内容。
2. ReactNode 可以接收哪些内容?
例如:
<MyComponent>你好</MyComponent>
<MyComponent>{123}</MyComponent>
<MyComponent>{true}</MyComponent>
<MyComponent><h1>Hello</h1></MyComponent>
<MyComponent>
<div>
<p>Hello</p>
<button>提交</button>
</div>
</MyComponent>
还可以传入:
- 字符串(string)
- 数字(number)
- React 元素(ReactElement)
- 多个 React 元素组成的数组
nullundefinedboolean- 其他 React 支持渲染的节点类型。
注意:true 和 false 可以作为 ReactNode,但不会在页面上显示文字。
3. ReactNode 和 JSX.Element 的区别
这两个类型很容易混淆。
| 类型 | 作用 |
|---|
| ReactNode | 表示所有 React 可以渲染的内容 |
| ReactElement | 表示一个 React 元素对象 |
| JSX.Element | TypeScript 对 JSX 表达式结果的类型 |
例如:
import { ReactNode } from 'react';
interface Props {
title: ReactNode;
content: ReactNode;
}
function Card({ title, content }: Props) {
return (
<div>
<header>{title}</header>
<main>{content}</main>
</div>
);
}
使用:
<Card
title={<h2>标题</h2>}
content={
<>
<p>第一段内容</p>
<p>第二段内容</p>
</>
}
/>
4. ReactNode 的典型使用场景
最常见的就是定义组件的 children 属性:
interface LayoutProps {
children: ReactNode;
}
function Layout({ children }: LayoutProps) {
return (
<div className="layout">
<header>网站头部</header>
<main>{children}</main>
<footer>网站底部</footer>
</div>
);
}
这样你就可以把任意 React 可渲染内容放到 Layout 里面。
记住这三个类型:
CSSProperties:定义 CSS 样式对象的类型。ReactNode:定义 React 可以渲染的内容类型。ReactElement:定义 React 元素对象的类型。
这三个在 React + TypeScript 开发中都非常常用。