【问题标题】:What is correct way how to create functional component in react using typescript如何使用打字稿在反应中创建功能组件的正确方法是什么
【发布时间】:2020-05-03 14:47:19
【问题描述】:

如何使用 typescript 在 react 中创建功能组件的正确方法是什么?

  1. 我应该使用interface 还是输入props
  2. 我应该使用React.FC 还是React.FunctionComponent
  3. 如何使用eslint 验证props

现在,我的典型组件如下所示:

interface IProps {
  color: string;
}

const Example = (props: IProps) => {
  const { color } = props;

  return (
    <>
      {color}
    </>
  );
};

我不确定这是否是最好的方法......

我也没有t know how to validate props usingeslint`,例如当我想将颜色作为数字传递时..

【问题讨论】:

  • React.FC 和 React.FunctionComponent 是一样的。
  • 你的代码就差不多了。您只需将const Example = (props: IProps) =&gt; { 更改为const Example: React.FC&lt;IProps&gt; = (props) =&gt; {。另外,你的界面很好!

标签: javascript reactjs typescript eslint


【解决方案1】:
  1. 两者都在社区中经常使用。我更喜欢type,因为我觉得它更容易使用,但你可以在这里阅读https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10 并发表你自己的意见。
  2. React.FCReact.FunctionComponent 的简写
  3. props 将通过 TypeScript 静态分析进行验证。

我发现这种模式在从函数组件开始时很有帮助:

type Props {
  color: string;
}

const Example: React.FC<Props> = ({color}: Props) => {

  return (
    <>
      {color}
    </>
  );
};

【讨论】:

  • 谢谢,有什么选项可以只从命令行运行TypeScript static analysis 吗?我想在 eslint 检查后提交之前运行它。还是您的意思是 TSLINT?
  • 如果您使用npx create-react-app my-app --template typescript 引导您的项目,默认情况下它已经存在,如果您违反 TypeScript 的规则,它会在运行npm start 时抱怨。要从命令行运行它,请参见例如这里stackoverflow.com/questions/33535879/…
【解决方案2】:

根据Maximilian Schwarzmüller 指南,最好的方法是:

import React from 'react';
import type { FC } from  'react';

interface SampleProps {
  color: string;
}

const Sample: FC<SampleProps> = ({ color }) => {
  return (
    <>
      {color}
    </>
  );
};

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多