使用React在Typescript中检查道具类型的最佳实践



下面,当与Typescript一起使用时,React中有两种类型检查道具的变体。

变体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 (
<></>
);
};

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

除了键入函数组件的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

最新更新