【问题标题】:Typescript React Functional Component with props.children带有 props.children 的 Typescript React 功能组件
【发布时间】:2020-12-30 08:30:28
【问题描述】:

我正在尝试制作一个组件,当 prop 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;

【问题讨论】:

    标签: reactjs typescript react-functional-component


    【解决方案1】:

    @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>
    

    【讨论】:

      【解决方案2】:

      那是因为return props.children

      你应该用一个片段来包装它,像这样:

      const Loading: React.FC<LoadingProps> = (props) => {
      return props.isLoading ? (
          <CircularProgress color={props.color || "primary"} />
        ) : (
          <>{props.children}</>
        );
      };
      

      【讨论】:

        【解决方案3】:

        建议(参见here)在使用 React.FunctionComponents 作为函数类型时明确定义子项的类型。

        所以

        type LoadingProps = {
            isLoading: boolean
            color: 'primary' | 'secondary' | 'inherit' | undefined
            children: React.ReactNode
        }
        

        这也将确保在返回时正确输入。

        【讨论】:

          猜你喜欢
          • 2020-08-14
          • 2020-10-22
          • 2020-12-20
          • 2020-06-18
          • 1970-01-01
          • 2023-04-04
          • 2017-04-06
          • 2019-11-29
          • 2020-06-25
          相关资源
          最近更新 更多