【问题标题】:What type do I specify for react components?我为反应组件指定什么类型?
【发布时间】:2019-10-05 09:00:39
【问题描述】:

非常直接的问题。 我来自 Qt/C++ 背景,因此我认为明确表达是一种好习惯,因此

protected sanityCheck() : void { ... } // Smart and beautiful
protected sanityCheck() { ... }        // Stupid and always wrong

好吧,我该如何明确:

protected toFoobar() : ?????
{
        return ( <h1> foobar </h1> );
}

当我检查文档时,它什么也没说。当我检查 typeof 时,它只是说 object。

这就是答案吗,或者我可以更具体吗?

谢谢。

【问题讨论】:

    标签: javascript reactjs typescript types typeof


    【解决方案1】:

    正确的类型是JSX.Element。这就是 JSX 语法总是计算的结果。如果你使用 React,JSX.Element 只是对React.Element&lt;any, any&gt; 的类型引用。

    【讨论】:

    • 那么我的代码行到底应该是什么?唯一有效的是protected toFoobar() : JSX.Element[],这看起来很奇怪。
    • @akiva 没有,JSX.Element.
    • Type 'Element[]' is missing the following properties from type 'Element': type, props, key TS2739
    • 不,我意识到你是对的;数组起作用的原因是我的 return 语句是一个 map 表达式。
    【解决方案2】:

    React 确实为 React 中的功能组件提供了类型 你可以这样做

    const toFoobar: React.FunctionComponent<IFoobar> = ({propsType}) => ();
    

    这是在 React.SFC 之前的 React 中的新功能

    希望对你有帮助

    【讨论】:

    • IFoobar 应该是什么?
    • 它的接口类似于 interface IFoobar{ name: string // 道具类型 }
    • 不起作用。 Type 'Element[]' provides no match for the signature '(props: PropsWithChildren&lt;Props_QPoll&lt;T&gt;&gt;, context?: any): ReactElement&lt;any, string | ((props: any) =&gt; ReactElement&lt;any, string | ... | (new (props: any) =&gt; Component&lt;any, any, any&gt;)&gt; | null) | (new (props: any) =&gt; Component&lt;...&gt;)&gt; | null'. TS2322 可能是因为我的 props 接口是泛型的。
    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 2015-06-14
    • 2022-01-09
    • 2022-12-11
    • 2023-04-02
    • 2017-05-23
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多