簡體   English   中英

如何將$ PropertyType用於react的函數無狀態組件?

[英]How use $PropertyType for function stateless components of react?

我需要獲得與$ 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)

您可以聲明類型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!

嘗試流程

此外,請查看如何使用$ Diff驗證可選字段? 有關如何鍵入React組件道具的更多提示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM