![](/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.