TypeScript和React-子类型?

reactjs React.js

Tom梅Green

2020-03-17

我有一个非常简单的功能组件,如下所示:

import * as React from 'react';

export interface AuxProps  { 
    children: React.ReactNode
 }


const aux = (props: AuxProps) => props.children;

export default aux;

还有另一个组件:

import * as React from "react";

export interface LayoutProps  { 
   children: React.ReactNode
}

const layout = (props: LayoutProps) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main>
            {props.children}
        </main>
    <Aux/>
);

export default layout;

我不断收到以下错误:

[ts] JSX元素类型'ReactNode'不是JSX元素的构造函数。类型'undefined'不能分配给'ElementClass'类型。[2605]

如何正确输入?

第1861篇《TypeScript和React-子类型?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
卡卡西梅Harry 2020.03.17

作为包含孩子的类型,我正在使用:

type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">

这种子容器类型足够通用,可以支持所有不同的情况,并且还与ReactJS API保持一致。

因此,以您的示例为例:

const layout = ({ children }: ChildrenContainer) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main>
            {children}
        </main>
    <Aux/>
)
Tony小胖 2020.03.17

从TypeScript站点:https : //github.com/Microsoft/TypeScript/issues/6471

建议的做法是将props类型写为{children ?: any}

那对我有用。子节点可以有很多不同的东西,因此显式键入可能会遗漏大小写。

这里有一个关于后续问题的更长的讨论:https : //github.com/Microsoft/TypeScript/issues/13618,但是任何方法仍然有效。

西里斯丁 2020.03.17

您可以这样声明您的组件:

const MyComponent: React.FunctionComponent = (props) => {
    return props.children;
}
Sam逆天 2020.03.17

这对我有用:

interface Props {
  children: JSX.Element[] | JSX.Element
}
TomNear前端 2020.03.17

为了<Aux>在您的JSX中使用,它必须是一个返回的函数ReactElement<any> | null那就是功能组件的定义

但是,当前定义为return的函数React.ReactNode,这是一个更广泛的类型。正如React类型所说的那样:

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

通过将返回的值包装到React Fragment(<></>中,确保不需要的类型被中和

const aux: React.FC<AuxProps> = props =>
  <>{props.children}</>;
古一小宇宙 2020.03.17

只是 children: React.ReactNode

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android