带有 props.children 的 Typescript React 功能组件

我正在尝试制作一个组件,当道具 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;
stack overflow Typescript React Functional Component with props.children
原文答案

答案:

作者头像

@sam256 的链接是正确的,但它表示通过 React.FunctionComponent 有一种新语法,其中子项是隐式的。

新语法:

const Title: React.FunctionComponent<{ title: string }> = ({
  children,
  title,
}) => <div title={title}>{children}</div>;

应该像这样工作:

<Title title="my string">
    <div>Implicit child</div>
</Title>