Jnl*_*Jnl 9 javascript typescript reactjs react-native react-props
我有一个看起来像这样的组件。这个版本完美运行:
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="" />
);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试更改导出它的方式。我正在尝试这个:
type StatusMessageProps = {
isAdded: boolean;
errorMessage: string;
}
export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
isAdded,
errorMessage
}) => {
Run Code Online (Sandbox Code Playgroud)
但我不断收到错误消息:
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'.
Run Code Online (Sandbox Code Playgroud)
I am using the same method on different pages but the error is only here
Run Code Online (Sandbox Code Playgroud)
编辑:
我正在像这样使用这个组件:
const [isAdded, setIsAdded] = useState(false);
{isSubmitted && StatusMessage(isAdded, errorMessage)}
Run Code Online (Sandbox Code Playgroud)
它给了我一个关于 isAdded 的错误
Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)
Run Code Online (Sandbox Code Playgroud)
小智 15
就我而言,我有一个身份验证包装器组件,如果身份验证正在加载或用户未经身份验证,则将返回加载页面组件,否则将返回子属性。
问题是我需要将子元素包裹在空的 html 标签中。
return <>{children}</>;
Run Code Online (Sandbox Code Playgroud)
tmh*_*005 10
您一定忘记了在组件中返回值。您是否忘记 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12888 次 |
| 最近记录: |