我有一个看起来像这样的组件。此版本可完美运行:
export default function StatusMessage(isAdded: boolean, errorMessage: string) {
if (isAdded) {
return <ResultAlert severity="success" text="User Added" />;
} else {
if (errorMessage !== '') {
if (
errorMessage.includes('email')
) {
return <ResultAlert severity="error" />;
}
if (
errorMessage.includes('phone number')
) {
return (
<ResultAlert severity="error" text="" />
);
}
}
}
}
现在,我正在尝试更改导出方式。我正在尝试:
type StatusMessageProps = {
isAdded: boolean;
errorMessage: string;
}
export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
isAdded,
errorMessage
}) => {
但是我不断收到错误消息:
Type '({ isAdded, errorMessage }: PropsWithChildren<StatusMessageProps>) => Element | undefined' is not assignable to type 'FunctionComponent<StatusMessageProps>'.
Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
I am using the same method on different pages but the error is only here
编辑:
我正在像这样使用此组件:
const [isAdded, setIsAdded] = useState(false);
{isSubmitted && StatusMessage(isAdded, errorMessage)}
在我的收藏夹上给我一个错误
Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)
答案 0 :(得分:3)
您必须忘了在组件中返回值。您是否会忘记返回null,因为void 0是React组件无法接受的结果?
export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
isAdded,
errorMessage
}) => {
if (isAdded) {
return <ResultAlert severity="success" text="User Added" />;
} else {
if (errorMessage !== '') {
if (
errorMessage.includes('email')
) {
return <ResultAlert severity="error" />;
}
if (
errorMessage.includes('phone number')
) {
return (
<ResultAlert severity="error" text="" />
);
}
}
// Here where you missed
return null;
}
}