我正在尝试制作一个组件,该组件将在 isLoading 属性为真时显示加载圆圈,否则显示子组件。我想像这样在其他组件中使用该组件...
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> );
我收到 typescript 错误
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;
最佳答案
建议(参见 here)在使用 React.FunctionComponents 作为您的函数类型时显式定义您的 child 的类型。
所以
type LoadingProps = {
isLoading: boolean
color: 'primary' | 'secondary' | 'inherit' | undefined
children: React.ReactNode
}
这也将确保在返回时正确输入。
关于reactjs - 带有 props.children 的 Typescript React 功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63853455/