【问题标题】:What is the correct typescript type for react children?反应儿童的正确打字稿类型是什么?
【发布时间】:2020-04-15 18:58:46
【问题描述】:

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

type Props = {
    children: any
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);

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

【问题讨论】:

  • 我用React.ReactNode
  • 您是否正在尝试将您的孩子键入特定的受控类型?如果没有,您可能应该使用React.PropsWithChildren&lt;MyProps&gt;。这会将默认子项添加到任何道具。

标签: reactjs typescript typescript-typings children react-props


【解决方案1】:

查看DefinitelyTyped 下的代码,children 似乎被键入为ReactNode

例子:

type Props = {
    children: ReactNode
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);

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

import React from 'react';

let someNode: React.ReactNode;

【讨论】:

    【解决方案2】:

    实际上,如果您使用React.FunctionComponent,则不必指定children

    例如下面的代码编译没有错误:

    const MyComponent: React.FC<{}> = props => {
      return props.children
    }
    

    【讨论】:

    • 我知道你不需要。为了完整起见,我喜欢在带有孩子的组件的道具上指定孩子。
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2017-08-03
    • 2020-05-31
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多