[英]Type JSX.Element is not assignable to type React.ReactNode when using customed conditional render component
I'm using next: "12.1.6" and react: "18.2.0".我正在使用下一个:“12.1.6”并做出反应:“18.2.0”。
I have a template component for conditional rendering.我有一个用于条件渲染的模板组件。
// Show.tsx
interface Props {
when: boolean;
fallback?: React.ReactNode;
children: React.ReactNode;
}
function Show(props: Props) {
if (props.when) {
return props.children;
}
return props.fallback ?? null;
}
export default Show;
and I use the template componenet like this but has an issue.我像这样使用模板组件但有问题。
<Show
when={connectionStatus}
fallback={
<div className="border rounded bg-red-400 py-2 px-5">
❌ disconnected
</div>
}
>
<div className="border rounded bg-green-400 py-2 px-5">
✅ connected
</div>
</Show>
at fallback
attribute, IDE represents an error "Type JSX.Element is not assignable to type React.ReactNode".在fallback
属性中,IDE 表示错误“Type JSX.Element is not assignable to type React.ReactNode”。
Both React.ReactElement
and JSX.Element
is a result of React.createElement
so I thought there is no specific difference between them except namespace. React.ReactElement
和JSX.Element
都是React.createElement
的结果,所以我认为除了命名空间之外它们之间没有特别的区别。 But it seems React.ReactNode
cannot cover JSX.Element
.但似乎React.ReactNode
无法覆盖JSX.Element
。
Waht should I update or change?我应该更新或更改什么?
ReactNode
is a ReactElement, a ReactFragment, a string, a number or an array of ReactNode ReactNode
是一个ReactElement,一个ReactFragment,一个字符串,一个数字或者一个ReactNode的数组
But in here you are returning an HTML template which is not part of above mentioned categories.但是在这里,您返回的是不属于上述类别的 HTML 模板。 Hence you need to change the type to JSX.Element
因此,您需要将类型更改为JSX.Element
fallback?: JSX.Element
Use Function to wrap fallback
JSX Element,使用 Function 包装fallback
JSX 元素,
like this:像这样:
<Show
when={connectionStatus}
fallback={() => {
return <div className="border rounded bg-red-400 py-2 px-5">
❌ disconnected
</div>
}}
>
<div className="border rounded bg-green-400 py-2 px-5">
✅ connected
</div>
</Show>
And update Props interface
to:并将Props interface
更新为:
interface Props extends React.PropsWithChildren<{
when: boolean;
fallback?: () => JSX.Element;
}> {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.