关于react.js:react-propTypes-Typescript

12次阅读

共计 2202 个字符,预计需要花费 6 分钟才能阅读完成。

最近看官网的文档,看到了 应用 PropTypes 进行类型查看 这一章节,看完之后发现这玩意和 typeScript 很相似,所以查找了一些材料,发现他们是能够相互转换的,上面来看一些例子:

根本类型的定义

PropTypes 写法:

// 当然要引入(以下省略)import PropTypes from 'prop-types';

Example.propTypes = {
  message: PropTypes.string, // 定义 string 类型
  count: PropTypes.number, // 定义 number 类型
  disabled: PropTypes.bool, // 定义 boolen 类型
  level: PropTypes.symbol, // 定义 symbol 类型
}

TypeScript 的写法:

interface Props {
  message: string;
  count: number;
  disabled: boolean;
  level: Symbol;
}

一些非凡的类型

PropTypes 写法:

Example.propTypes = {error: PropTypes.instanceOf(Error), // 是否是 error 实例
  children: PropTypes.node, // 定义 元素
  status: PropTypes.oneOf(['inactive', 'inProgress', 'success', 'failed']), // 定义指定值,必须为 'inactive', 'inProgress', 'success', 'failed' 中的一个
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Error),
  ]), // 必须为这几种类型中的一种
}

TypeScript 的写法:

interface Props {
  error: Error;
  children: React.ReactNode;
  status: 'inactive' | 'inProgress' | 'success' | 'failed';
  value: string | number | Error;
}

数组和对象

PropTypes 写法:

Example.propTypes = {
  style: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number,
  }), // 指定这个对象由特定的类型值组成
  person: PropTypes.exact({
    name: PropTypes.string,
    age: PropTypes.number,
    employed: PropTypes.bool,
    status: PropTypes.oneOf([
      'single',
      'dating',
      'engaged',
      'married',
      'divorced',
      'widowed',
      'other',
    ]),
  }), // // An object with warnings on extra properties
  names: PropTypes.arrayOf(PropTypes.string), // 必须 值全是 string 类型的数组
  items: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number,
      title: PropTypes.string,
      active: PropTypes.boolean,
    }),
  ),
}

TypeScript 的写法:

interface Props {
  style: {
    color: string
    fontSize: number
  };
  person: {
    name: string
    age: number
    employed: boolean
    status:
      | 'single'
      | 'dating'
      | 'engaged'
      | 'married'
      | 'divorced'
      | 'widowed'
      | 'other'
  };
  names: string[];
  items: {
    id: number
    title: string
    active: boolean
  }[];}

函数
PropTypes 写法:

Example.propTypes = {
  onClick: PropTypes.func,
  onChange: PropTypes.func,
  onSelect: PropTypes.func,
}

TypeScript 的写法:

interface Props {onClick: () => void
  onChange: (val: string) => void
  onSelect: (id: string, val: number) => void
}

必须参数的写法

PropTypes 写法:

Example.propTypes = {
  description: PropTypes.string.isRequired,
  isActive: PropTypes.bool,
}

TypeScript 的写法:

interface Props {
  description: string
  isActive?: boolean
}

总结

在 TypeScript React 应用程序中应用 PropTypes 没有什么太大的价值,通过下面的例子也能够看出 TypeScript 的写法比较简单易懂

参考:

React Prop Types with TypeScript
PropTypes in a TypeScript React Application

正文完
 0