如何使用打字稿在反应中创建功能组件的正确方法是什么 [英] What is correct way how to create functional component in react using typescript
本文介绍了如何使用打字稿在反应中创建功能组件的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用打字稿在反应中创建功能组件的正确方法是什么?
What is correct way how to create functional component in react using typescript ?
- 我应该使用
interface
或键入道具
? - 我应该使用
React.FC
或React.FunctionComponent
? - 如何验证
道具
使用eslint
?
- Should I use
interface
or type forprops
? - Should I use
React.FC
orReact.FunctionComponent
? - How can I validate
props
usingeslint
?
现在,我通常使用的组件如下:
Right now, my typically components looks like:
interface IProps {
color: string;
}
const Example = (props: IProps) => {
const { color } = props;
return (
<>
{color}
</>
);
};
我不确定这是否是最好的方法...
I am not sure if it best way...
我也不知道如何使用来验证道具,例如,当我想将颜色作为数字传递时。
Also I dont know how to validate props using
eslint`, for example when I want to pass down color as a number..
推荐答案
- 两者在社区中都经常使用。我更喜欢
type
,因为它更易于使用,但是您可以在此处阅读 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10 并发表您自己的看法。 -
React.FC
是React.FunctionComponent
的简写 - 道具将通过TypeScript静态分析进行验证。
- Both are used frequently in the community. I prefer
type
as I find it easier to use, but you can read here https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10 and make your own opinion. React.FC
is shorthand forReact.FunctionComponent
- props will be validated by the TypeScript static analysis.
从功能组件开始,我发现此模式很有用:
I found this pattern helpful when starting with function components:
type Props {
color: string;
}
const Example: React.FC<Props> = ({color}: Props) => {
return (
<>
{color}
</>
);
};
这篇关于如何使用打字稿在反应中创建功能组件的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文