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

标签 reactjs typescript react-functional-component

我正在尝试制作一个组件,该组件将在 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/

相关文章:

javascript - 如何修复 "TypeError: Cannot set property ' 已批准“为空”?

reactjs - React-Redux:如何从异步 AJAX 调用的响应中设置初始状态?

typescript - 在 Angular2 项目中使用 TweenMax

reactjs - 测量组件在 React Native 功能组件中渲染的次数

javascript - react : How to create state dependent function in functional components?

javascript - 在 React 中,我可以在另一个功能组件的主体内定义一个功能组件吗?

javascript - 使用connected-react-router在React + Redux中推送状态

reactjs - 如何在 vscode webview 中使用acquireVsCodeApi [React]

javascript - Angular 2 : What is an @Input/@Output alias?

typescript - 添加自定义@types 的 js 库还没有它