我有一个非常简单的功能组件如下
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]
我该如何正确输入?
这对我有用:
interface Props {
children: JSX.Element[] | JSX.Element
}
为了在JSX中使用<Aux>
,它需要是一个返回ReactElement<any> | null
的函数。这是功能组件的定义。
但是,它目前被定义为返回React.ReactNode
的函数,type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
是一种更宽泛的类型。正如React打字所说:
<></>
通过将返回的值包装到React Fragment(const aux: React.FC<AuxProps> = props =>
<>{props.children}</>;
)中,确保中和不需要的类型:
https://github.com/Microsoft/TypeScript/issues/6471
来自TypeScript网站:https://github.com/Microsoft/TypeScript/issues/13618
建议的做法是将道具类型写为{children ?: any}
这对我有用。子节点可以有许多不同的东西,因此显式输入可能会遗漏案例。
关于跟进问题的讨论时间较长:qazxsw poi,但任何方法仍然有效。
React组件应该有一个包装器节点或返回一个节点数组。
你的<Aux>...</Aux>
组件有两个节点div
和main
。
尝试将你的孩子包裹在div
组件中的Aux
中。
import * as React from 'react';
export interface AuxProps {
children: React.ReactNode
}
const aux = (props: AuxProps) => (<div>{props.children}</div>);
export default aux;