[英]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.