[英]Typescript: Type 'Element[]' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>'
我有一个组件声明如下:
const Wrapper = ({children}: {children: ReactElement[]}): ReactElement => {
return (
<div className="wrapper">
{children}
</div>
);
};
这个包装器需要一个 ReactElement 数组,例如:
<Wrapper>
{items.map((item, index) => {
return (
<Item />
)
})}
</Wrapper>
这工作正常,但是当我想将一个 div 添加到返回的项目列表时,如下所示:
<Wrapper>
<div /> {/* empty div for the first column */}
{items.map((item, index) => {
return (
<Item />
)
})}
</Wrapper>
我收到此错误:
Type 'Element[]' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>'.ts(2322)
我该如何解决这个问题?
通常 Rect 组件意义上的children
项的正确类型是ReactNode
(注意它不是数组):
const Wrapper = ({ children }: { children: ReactNode }): ReactElement => {
return <div className="wrapper">{children}</div>;
};
const Item = () => <div />;
const items = [1, 2, 3];
const x = (
<Wrapper>
<div />
{items.map((item, index) => {
return <Item />;
})}
</Wrapper>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.