确保数组属性的每个元素都符合 React 中的自定义形状 [英] Ensuring each element of an array property conforms to custom shape in React

查看:47
本文介绍了确保数组属性的每个元素都符合 React 中的自定义形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保数组属性的每个元素都符合特定的形状.

I want to ensure every element of an array property conforms to a particular shape.

这与 React proptype array with shape.他们测试了每个元素是否与给定的预定义 React proptype 验证器匹配,在这种情况下为 React.propTypes.number.我有兴趣针对自定义对象形状进行测试.

This is different than the question answered in React proptype array with shape. They tested if every element matched a given pre-defined React proptype validator, in that case React.propTypes.number. I'm interested testing against a custom object shape.

例如:

class MyClass extends React.Component {
  constructor(props) {
    super(props);
  }

  static propTypes = {
    data: React.PropTypes.arrayOf({
      name: React.PropTypes.string,
      year: React.PropTypes.number,
    })
  }
}

这会触发警告:Failed propType: typeChecker is not a function 检查渲染方法

推荐答案

你已经接近了,但是你需要指定数组属于哪种类型的 proptype,然后 React.PropTypes.shape 让我们您指定一个带有键及其类型的对象.

You're close, but you need to specify what kind of proptype the array is of, and React.PropTypes.shape let's you specify an object with keys and their types.

static propTypes = {
  data: React.PropTypes.arrayOf(
    React.PropTypes.shape({
      name: React.PropTypes.string,
      year: React.PropTypes.number,
    })
  )
}

提示:做 import React, { PropTypes } from 'react' 这样你就可以使用 PropTypes.

tip: do import React, { PropTypes } from 'react' so you can just use PropTypes.

这篇关于确保数组属性的每个元素都符合 React 中的自定义形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆