为IF ELSE添加附加条件



我正在构建我的第一个Ionic React应用程序,并创建了一个简单的自定义组件,该组件基于两个可选的输入值返回内容。

当我有一个简单的if/else if/else条件时,组件呈现得很好,但是添加一个额外的'else if'会阻止它编译,我还不能确定为什么。

下面是工作组件:

import React from 'react';
import './CardContainer.css';
interface ContainerProps {
position?: string;
content?: string;
}
const CardContainer: React.FC<ContainerProps> = ({ position = "right", content = "n/a"}) => {
let cardOutput;
if ( position.trim().toLowerCase() === "right" ) {
cardOutput = <><div className="ion-float-right">{content}</div><div className="clear-right"></div></>;
} else if ( position.trim().toLowerCase() === "left" ) {
cardOutput = <div className="ion-float-left">{content}</div>;
} else {
cardOutput = <div className="ion-float-left">{content}</div>;
}
return (
cardOutput
)
};

export default CardContainer;

下面是无法编译的代码:

import React from 'react';
import './CardContainer.css';
interface ContainerProps {
position?: string;
content?: string;
}
const CardContainer: React.FC<ContainerProps> = ({ position = "right", content = "n/a"}) => {
let cardOutput;
if ( position.trim().toLowerCase() === "right" ) {
cardOutput = <><div className="ion-float-right">{content}</div><div className="clear-right"></div></>;
} else if ( position.trim().toLowerCase() === "left" ) {
cardOutput = <div className="ion-float-left">{content}</div>;
} else if ( position.trim().toLowerCase() === "empty" ) {
cardOutput = <div className="ion-padding-top">{content}</div>;
}
return (
cardOutput
)
};
export default CardContainer;

唯一显著的区别是我用'else if'替换了'else'条件。我已经尝试添加'else'条件只是为了消除可能的原因,这并不能解决问题。

当我尝试在我的开发系统上运行应用程序时,我得到这样的输出:

Type '({position, content}: PropsWithChildren) =>Element | undefined'不能赋值给类型'FC'。类型'Element | undefined'不能赋值给TypeReactElement<任何any>|空"。类型'undefined'不能赋值给type 'ReactElement<any,>|零".ts (2322)

对于我没有经验的眼睛来说,这并没有给我太多的指示,除了它与TypeScript有关的问题。

这是因为您的数据可能位于if条件中,因此声明的cardoutput变量仍然未定义。

let cardOutput;//undefined

所以尝试使用else条件,这样cardoutput就不会是undefined

你是对的,这是一个TypeScript错误,更具体地说,TypeScript期望CardContainer是一个功能组件,但你当前的代码使CardContainer有可能返回Undefined,因此错误识别组件类型为Element | undefined

如果没有else条件,默认的else行为是返回未定义的cardOutput(因为它不属于任何定义它的if或if/else语句)。

最新更新