我正试图在typescript中实现条件渲染,目前当null
被用作替代方案时,我收到以下错误消息
"类型"Element|null"不可分配给类型"Element"。类型"null"不可分配给类型"ReactElement<任意,任意>'">
所以,如果我删除JSX.Element
,那么typescript会在返回函数中抱怨缺少类型。另一种选择是用(<></>)
代替null
。这是有效的,但我在某个地方读到这会占用dom中的额外空间,所以null是更好的解决方案。那么,有没有函数返回类型可以处理null或其他方法呢?
export const ContextPanel = ({
children,
}: React.PropsWithChildren<LayoutContextInterface>): JSX.Element => {
const context = React.useContext(LayoutContext);
return context.contextPanelOpen ? (
<div className={styles.contextPanelWidth}>{children}</div>
) : null;
};
我建议使用FunctionComponent类型(如果你想自己手动键入,请查看它以了解正确返回类型的详细信息。
export const ContextPanel: React.FunctionComponent = ({
children
}) => {
const context = React.useContext(LayoutContext);
return context.contextPanelOpen ? (
<div className={styles.contextPanelWidth}>{children}</div>
) : null;
};
以下是编写本答案时对FunctionComponent
接口的定义,以供参考。请参阅链接以获取最新版本。
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P> | undefined;
contextTypes?: ValidationMap<any> | undefined;
defaultProps?: Partial<P> | undefined;
displayName?: string | undefined;
}
请注意,此处的返回类型为ReactElement<any, any> | null
。我怀疑,如果你只是用JSX.Element | null
正确地键入你的报税表,你最初的答案会起作用,但总的来说,这种键入可能更准确。