reactjs - 在 TypeScript 中,何时使用 <> 以及何时使用 :
问题描述
我不明白什么时候应该使用<>
,什么时候应该使用:
来为属性分配类型。我有下面的代码是正确的,但我不知道为什么我声明React.FunctionComponent<Props>
而不是React.FunctionComonent : Props
interface Props {
speakers : Speaker[]
}
const SpeakersMain : React.FunctionComponent<Props> = (props : Props) => (
<div>
<SpeakersHeader/>
<SpeakerList speakers={props.speakers} />
</div>
);
解决方案
const SpeakersMain: React.FunctionComponent<Props> = ...;
应该使用,因为使用:
afterReact.FunctionComponent
将是不正确的语法。
SpeakersMain: React.FunctionComponent
意味着SpeakersMain
变量是React.FunctionComponent
类型的。虽然<Props>
添加了说明,因为在 React类型中React.FunctionComponent
被定义为泛型类型。<>
语法允许Props
作为参数传递。
React.FunctionComponent<Props>
type 意味着它是一个以Props
type 作为props
参数的函数。
它的工作原理是:
type Foo<T = {}> = (props: T) => void;
type Bar = { bar: number };
var foo1: Foo = (props) => { /* props is supposed to be empty object by default */ };
var foo2: Foo<Bar> = (props) => { /* props is supposed to be Bar */ };
推荐阅读
- javascript - 云功能速率限制器,不返回数据
- phpstorm - PHPStorm 找不到内置服务器的文件 (HTTP 404)
- asp.net - 更新变量的值不起作用 ASP.NET Core Web API
- python-3.x - 如何从列表中的 int 元素中连续减去值,直到到达列表末尾?
- python - 自定义用户模型 Django 上的外键
- powershell - 从文件名中提取日期,然后按日期升序处理文件 - Powershell
- javascript - 单击按钮时内部的图像随机化器功能
- html - 无法在输入框中选择文本
- c# - 控件类型作为数据列的数据类型
- bluetooth - hcitool不配对显示iOS13的公共Mac地址