maj*_*mer 222 arrays reactjs react-proptypes
是否有内置的方法来使用proptypes来确保传递给组件的对象数组实际上是特定形状的对象数组?
也许是这样的?
annotationRanges: PropTypes.array(PropTypes.shape({
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
})),
Run Code Online (Sandbox Code Playgroud)
我错过了一些非常明显的东西吗?看起来像这样会受到高度追捧.
Pie*_*scy 334
您可以使用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,
}
Run Code Online (Sandbox Code Playgroud)
请参阅文档的Prop Validation部分.
UPDATE
截至react v15.5,React.PropTypes不推荐使用use,而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,
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*eza 44
是的,你需要使用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
}
Run Code Online (Sandbox Code Playgroud)
有关proptypes的更多详细信息,请访问此处的Typechecking With PropTypes
maj*_*mer 26
它就在我的鼻子底下......
来自反应文档本身:https://facebook.github.io/react/docs/reusable-components.html
// An array of a certain type
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
Run Code Online (Sandbox Code Playgroud)
有一个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: [],
}
}
Run Code Online (Sandbox Code Playgroud)