如何将$ PropertyType用于react的函数无状态组件?

时间:2019-07-24 11:28:07

标签: javascript reactjs flow

我需要获取要与$ PropertyType实用程序一起使用的功能组件的类型。我该如何为我完成错误的工作?



// This code not work with component as function

function Button({loading, children}: {|
    loading: boolean,
    children: string,
|}) {
    return (
        <button>
            {children}
            {loading && <div className="loading"/>}
        </button>
    )
};

function SpecialButton({loading}: {|
    loading: $PropertyType<$PropertyType<typeof Button, 'props'>, 'loading'>
|}) {
    return (
        <div>
            <Button loading={loading}>
                special text
            </Button>
        </div>
    )
}

const specButton = <SpecialButton loading={10000}/> // <-- no error
// (its NOT OK for me)

1 个答案:

答案 0 :(得分:0)

您可以声明类型ButtonProps并在其上使用$PropertyType吗?

import React from 'react';

type ButtonProps = {| loading: boolean, children: string |};
type SpecialButtonProps = {| loading: $PropertyType<ButtonProps, 'loading'> |};

function Button({ loading, children }: ButtonProps) {
    return (
        <button>
            {children}
            {loading && <div className="loading"/>}
        </button>
    )
};

function SpecialButton({ loading }: SpecialButtonProps) {
    return (
        <div>
            <Button loading={loading}>
                special text
            </Button>
        </div>
    )
}

const specButton = <SpecialButton loading={10000} /> // Error!

Try Flow

另外,请查看How to validate optional fields with `$Diff`?,以获得有关如何键入React组件道具的更多提示。