您的位置:首页 > Web前端 > React

React PropTypes

2015-10-20 00:00 387 查看
PropTypes用于指定component参数类型或是否required等,起到校验作用,使用PropTypes有两个好处:

1. You can easily open up a component and check which props are required and what type they should be.
2. When things get messed up React will give you an awesome error message in the console, saying which props is wrong/missing plus the render method that caused the problem.

PropTypes中的参数类型有:

React.createClass({
propTypes: {

optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,

// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: React.PropTypes.node,

// A React element.
optionalElement: React.PropTypes.element,

// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: React.PropTypes.instanceOf(Message),

// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),

// An object that could be one of many types
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Message)
]),

// An array of a certain type
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

// An object with property values of a certain type
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),

// An object taking on a particular shape
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),

// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: React.PropTypes.func.isRequired,    //参数为function,且必须

// A value of any data type
requiredAny: React.PropTypes.any.isRequired,

//自定义参数校验类型
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error('Validation failed!');
}
}
},
/* ... */
});

如果参数传入不正确,则console会出现类似以下warning:



如果指定了propTypes,但使用Component时不想传入任何参数,可以使用getDefaultProps();

var ComponentWithDefaultProps = React.createClass({
getDefaultProps: function() {
return {
value: 'default value'
};
}
/* ... */
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: