Proptypes自定义验证器与Flow

时间:2018-02-16 13:13:10

标签: reactjs flowtype

我有一个Paginator组件,其Flow的道具验证工作方式如下:

type Props = {
  totalPages?: number,
  currentPage?: number,
  onClickPage?: Function
}

现在我想为currentPage创建一个自定义验证器,特别是它需要等于或小于totalPages

对于proptypes,我会这样做:

currentPage: (props, propName, component) => {
  if (currentPage > totalPages)
    return new Error(
      `{Invalid props ${propName} supplied to ${component}: ${propName} needs to be equal or less than totalPages.}`
    )
}

但是如何使用Flow Type?

2 个答案:

答案 0 :(得分:0)

请参阅此处 - flow.org/Try

type Props = {
  totalPages?: number,
  currentPage?: number,
  onClickPage?: Function
}

currentPage: (props: Props, propName: string, component: string) => {
  if (props[propName] > props.totalPages)
    return new Error(
      `{Invalid props ${propName} supplied to ${component}: ${propName} needs to be equal or less than totalPages.}`
    )
}

答案 1 :(得分:0)

我找不到使用流式输入实现此功能的方法,但looks like a good solution to this使用的是与invariantwarning一起输入的流,并使用componentWillMount方法:

  componentWillMount = () => {
    warning(
      this.props.currentPage <= this.props.totalPages,
      'Your currentPage prop value is out of range'
    );
  }