ReactNode 类型
在 React + TS 中,children 的类型通常写成 ReactNode
什么是 ReactNode
在 @types/react 里定义大概是这样的(简化版)
type ReactNode =| ReactElement // <div />、<MyComp />| string // "hello"| number // 123| boolean // true/false(但渲染时会忽略)| null // 不渲染| undefined // 不渲染| ReactNode[] // 数组,比如 ["a", <div/>]
👉 它几乎涵盖了 JSX 中 所有可能被渲染 的内容。
在组件里传 children 的场景
比如写一个容器组件:
import { ReactNode } from "react"interface Props {children: ReactNode
}const Card = ({ children }: Props) => {return <div className="card">{children}</div>
}export default Card
使用时,这里 <h1>Hello</h1><p>World</p>
就作为 children 传进 Card,类型是 ReactNode
<Card><h1>Hello</h1><p>World</p>
</Card>
为什么用 ReactNode
ReactNode 更宽泛,能匹配 几乎所有 React 可以渲染的东西
其他类型:
- any 不好看
- JSX.Element 只能接收 单个 JSX 节点(不支持 string、number、数组、null 等)