我试图制作一个组件,当道具isLoading为true时,该组件将显示一个加载循环,否则将显示子组件。我想在其他类似的组件中使用该组件。。。
import Loading from './Loading.tsx'
...
const [isLoading,setLoading] = React.useState(false);
return (
<Loading isLoading={isLoading}>
<div>this component will show when loading turns to true</div>
</Loading> );
我得到了脚本错误
Type '({ isLoading, color, children, }: PropsWithChildren<LoadingProps>) => Element | { children: ReactNode; }' is not assignable to type 'FunctionComponent<LoadingProps>'.
Type 'Element | { children: ReactNode; }' is not assignable to type 'ReactElement<any, any> | null'.
Type '{ children: ReactNode; }' is missing the following properties from type 'ReactElement<any, any>': type, props, key TS2322
有人能指出我做错了什么吗?
import React, { FunctionComponent } from 'react';
import { CircularProgress } from '@material-ui/core';
type LoadingProps = {
isLoading: boolean;
color: 'primary' | 'secondary' | 'inherit' | undefined;
};
const Loading: FunctionComponent<LoadingProps> = (props) => {
if(props.isLoading){
return <CircularProgress color={props.color || 'primary'} />
}
return props.children;
};
export default Loading;
建议(请参见此处)在使用React时显式定义孩子的类型。函数组件作为函数类型。
所以呢
type LoadingProps = {
isLoading: boolean
color: 'primary' | 'secondary' | 'inherit' | undefined
children: React.ReactNode
}
这也将确保在返回时输入正确。
这是因为返回道具。儿童
。
您应该用一个片段包装它,如下所示:
const Loading: React.FC<LoadingProps> = (props) => {
return props.isLoading ? (
<CircularProgress color={props.color || "primary"} />
) : (
<>{props.children}</>
);
};