是否有一种内置的方法来使用 proptypes 来确保传递给组件的对象数组实际上是特定形状的对象数组?
也许是这样的?
annotationRanges: PropTypes.array(PropTypes.shape({
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
})),
我在这里错过了一些非常明显的东西吗?似乎这将受到高度追捧。
是否有一种内置的方法来使用 proptypes 来确保传递给组件的对象数组实际上是特定形状的对象数组?
也许是这样的?
annotationRanges: PropTypes.array(PropTypes.shape({
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
})),
我在这里错过了一些非常明显的东西吗?似乎这将受到高度追捧。
您可以将React.PropTypes.shape()
其用作以下参数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,
}
请参阅文档的Prop Validation部分。
更新
从 开始react v15.5
, usingReact.PropTypes
已被弃用,而prop-types
应使用独立包:
// 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,
}
是的,您需要使用PropTypes.arrayOf
而不是PropTypes.array
在代码中,您可以执行以下操作:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
annotationRanges: PropTypes.arrayOf(
PropTypes.shape({
start: PropTypes.string.isRequired,
end: PropTypes.number.isRequired
}).isRequired
).isRequired
}
此外,有关proptypes的更多详细信息,请在此处访问使用 PropTypes进行类型检查
它就在我的鼻子底下:
从反应文档本身:https ://facebook.github.io/react/docs/reusable-components.html
// An array of a certain type
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
有一个 ES6 速记导入,你可以参考。更具可读性和易于输入。
import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';
class ExampleComponent extends Component {
static propTypes = {
annotationRanges: arrayOf(shape({
start: number,
end: number,
})).isRequired,
}
static defaultProps = {
annotationRanges: [],
}
}
如果我要为特定形状多次定义相同的 proptypes,我喜欢将其抽象到一个 proptypes 文件中,这样如果对象的形状发生变化,我只需在一个地方更改代码。它有助于使代码库有点干涸。
例子:
// Inside my proptypes.js file
import PT from 'prop-types';
export const product = {
id: PT.number.isRequired,
title: PT.string.isRequired,
sku: PT.string.isRequired,
description: PT.string.isRequired,
};
// Inside my component file
import PT from 'prop-types';
import { product } from './proptypes;
List.propTypes = {
productList: PT.arrayOf(product)
}
这也是我防止空数组的解决方案:
import React, { Component } from 'react';
import { arrayOf, shape, string, number } from 'prop-types';
ReactComponent.propTypes = {
arrayWithShape: (props, propName, componentName) => {
const arrayWithShape = props[propName]
PropTypes.checkPropTypes({ arrayWithShape:
arrayOf(
shape({
color: string.isRequired,
fontSize: number.isRequired,
}).isRequired
).isRequired
}, {arrayWithShape}, 'prop', componentName);
if(arrayWithShape.length < 1){
return new Error(`${propName} is empty`)
}
}
}