用形状反应 proptype 数组 [英] React proptype array with shape
本文介绍了用形状反应 proptype 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有使用 proptypes 的内置方法来确保传递给组件的对象数组实际上是特定形状的对象数组?
Is there a built-in way to use proptypes to ensure that an array of objects being passed to a component is actually an array of objects of a specific shape?
也许是这样?
annotationRanges: PropTypes.array(PropTypes.shape({
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
})),
我在这里遗漏了一些非常明显的东西吗?看来这会很受追捧.
Am I missing something super obvious here? Seems like this would be highly sought after.
推荐答案
你可以使用 React.PropTypes.shape()
作为 React.PropTypes.arrayOf()
的参数代码>:
You can use React.PropTypes.shape()
as an argument to React.PropTypes.arrayOf()
:
// an array of a particular shape.
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired,
})).isRequired,
}
请参阅文档的道具验证部分.
更新
从 react v15.5
开始,不推荐使用 React.PropTypes
,而应使用独立包 prop-types
代替:
As of react v15.5
, using React.PropTypes
is deprecated and the standalone package prop-types
should be used instead :
// an array of a particular shape.
import PropTypes from 'prop-types'; // ES6
var PropTypes = require('prop-types'); // ES5 with npm
ReactComponent.propTypes = {
arrayWithShape: PropTypes.arrayOf(PropTypes.shape({
color: PropTypes.string.isRequired,
fontSize: PropTypes.number.isRequired,
})).isRequired,
}
这篇关于用形状反应 proptype 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文