![](/img/trans.png)
[英]Typescript: Type 'Element[]' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>'
[英]Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any)
我有一个看起来像这样的组件。 这个版本完美运行:
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)}
它在 isAdded 上给我一个错误
Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)
您一定忘记了在组件中返回一个值。 您是否忘记了 return 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;
}
}
在我的例子中,我有一个 auth 包装器组件,如果正在加载 auth 或用户未通过身份验证,将返回一个加载页面组件,否则将返回 children 道具。
问题是我需要将孩子包裹在空的 html 标签中。
return <>{children}</>;
在我的例子中return null;
没有用,所以我return <></>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.