对于反应儿童来说,正确的打字稿类型是什么?

lin*_*dan 20 children typescript reactjs typescript-typings react-props

我正在尝试正确输入映射子组件的道具:

type Props = {
    children: any
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);
Run Code Online (Sandbox Code Playgroud)

我一直在用JSX.Element,但感觉不太对劲。

lin*_*dan 36

查看DefinitelyTypedchildren下的代码,它的类型似乎是ReactNode

例子:

type Props = {
    children: ReactNode
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);
Run Code Online (Sandbox Code Playgroud)

注意:该ReactNode类型可以在 React 命名空间中找到:

import React from 'react';

let someNode: React.ReactNode;
Run Code Online (Sandbox Code Playgroud)

  • 如果组件可选地接受子组件,那么 `children?: React.ReactNode` 是正确的类型。 (6认同)