如何使用打字稿在反应中创建功能组件的正确方法是什么 [英] What is correct way how to create functional component in react using typescript

查看:83
本文介绍了如何使用打字稿在反应中创建功能组件的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用打字稿在反应中创建功能组件的正确方法是什么?

What is correct way how to create functional component in react using typescript ?


  1. 我应该使用 interface 或键入道具

  2. 我应该使用 React.FC React.FunctionComponent

  3. 如何验证道具使用 eslint

  1. Should I use interface or type for props?
  2. Should I use React.FC or React.FunctionComponent?
  3. How can I validate props using eslint?

现在,我通常使用的组件如下:

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 usingeslint`, for example when I want to pass down color as a number..

推荐答案


  1. 两者在社区中都经常使用。我更喜欢 type ,因为它更易于使用,但是您可以在此处阅读 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10 并发表您自己的看法。

  2. React.FC React.FunctionComponent
  3. 的简写
  4. 道具将通过TypeScript静态分析进行验证。

  1. 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.
  2. React.FC is shorthand for React.FunctionComponent
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆