【问题标题】:Best practice for type checking props in Typescript with React使用 React 在 Typescript 中类型检查 props 的最佳实践
【发布时间】:2020-07-15 11:34:49
【问题描述】:

下面我在 React 中使用 Typescript 时有两种类型检查道具的变体。

变化 1

interface Props {
  prop1: string,
  prop2: string,
}

const MyComponent = ({ prop1, prop2 }: Props) => {
  return (
    <></>
  );
};

变体 2

interface Props {
  prop1: string,
  prop2: string,
}

const MyComponent: React.FC<Props> = (props) => {
  const { prop1, prop2 } = props;
  return (
    <></>
  );
};

以上哪些变体被认为是最佳实践,为什么?

【问题讨论】:

  • 函数组件使用FC&lt;P&gt;。它免费为您提供您没有想到的其他道具(例如children)。

标签: reactjs typescript typechecking react-typescript


【解决方案1】:

除了输入函数组件的props之外,您还可以输入React.FC/React.FunctionComponent(它们相同,只是简写)作为第二个示例。

一些区别是:

  • React.FC 是明确的返回类型,而普通函数版本是隐式的(或者需要额外的注释)。
// Implicit return type
const MyComponent = ({ prop1, prop2 }: Props) => {
  return (
    <></>
  );
};
  • 它为displayNamepropTypesdefaultProps 等静态属性提供类型检查和自动完成功能。
// Typing MyComponent.
// Will autocomplete `displayName`, `propTypes`, `defaultProps` etc
  • 它提供了children 的隐式定义
// Implicit definition of children property
const MyComponent: React.FC<Props> = ({ children, prop1, prop2 }) => {
  return (
    <></>
  );
};

以上哪些变体被认为是最佳实践,为什么?

通常React.FC 用于键入函数组件,常识是将其与类似于第一个变体的“返回 React 元素的函数”区别开来。

// Some helper function which returns React element
// But not a component like the first variant
const helperFunction = (args:Args) => {...}
// ^ typing with React.FC will give it a meaning of function component

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2020-11-12
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多