我是一个新的反应和打字的人。
我发现我需要这样声明道具:
const Title = ({title}:{[key:string]:any}) => {但对我来说,这似乎有点费解。有没有更好的方法来解决这个问题呢?
发布于 2020-04-17 08:58:28
如果你愿意,你可以通过声明一个带有你期望的所有道具的接口来保持它的简单性:
interface MyProps {
A: string;
B: number;
C?: number; // C is optional
}
const MyComponent = ({ A, B }: MyProps) => { ... }发布于 2020-04-17 08:59:42
我建议使用FC泛型(这是FunctionComponent泛型的别名)。我更喜欢使用它,而不是不使用泛型,因为它附加了children属性,并键入了函数组件React.Element vs JSX.Element的返回值。
import * as React from "react";
import {FC} from "react";
interface ITitleProps {
title: string;
}
// This works as expected
export const Title1: FC<ITitleProps> = ({
title,
children // Added by 'FC'
}) => {
return (
<div>
<h1>{title}</h1>
<p>{children}</p>
</div>
);
};
// This produces an error
export const Title2 = ({
title,
children // property 'children' does not exist on type 'ITitleProps'
}: ITitleProps) => {
return (
<div>
<h1>{title}</h1>
<p>{children}</p>
</div>
);
};这个GitHub试图弄清楚如何在React:React TypeScript Cheatsheet中使用TS是非常有价值的
https://stackoverflow.com/questions/61262433
复制相似问题