【问题标题】:Understanding React.FC in Typescript理解 Typescript 中的 React.FC
【发布时间】:2020-11-01 18:42:52
【问题描述】:

我一直在尝试了解 React.FC 类型的工作原理,并尝试了多种方法,这是唯一有效的方法:

import React from 'react'
    
    type iProps<P = {}> = {
        (props: P): React.ReactElement<any, any>
    }
    
    interface IPropsTest {
        name: string,
        age: number
    }
    
    const MyComponent: iProps<IPropsTest> = ({ name, age }) => {
        return <div>{name} {age}</div>
    }

谁能解释一下这部分

type iProps<P = {}> = {
    (props: P): React.ReactElement<any, any>
}

为什么我需要&lt;P = {}&gt;,为什么我必须输入(props: P)

【问题讨论】:

  • 你想做什么?你甚至没有在这里使用FC 类型
  • 你在概念上理解 Typescript 泛型吗?如果没有,从那里开始。

标签: typescript react-typescript


【解决方案1】:

什么是P = {}

这是一个通用默认值。如果未提供通用参数,则假定 P{}

为什么一定要放(props: P)

这意味着可以预期该函数将使用P 类型的一个参数调用。

【讨论】:

    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 2020-11-14
    • 2022-01-23
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多