我想直观地测试React组件.用户可以使用表单更改组件的道具.我希望能够(例如)基于渲染
React.PropTypes.oneOf(['green', 'blue', 'yellow'])
.
当我读到MyComponent.propTypes
它时,返回由React定义的函数.有没有办法提取/读取道具类型?
您无法直接阅读,propTypes
因为正如您所说,它们被定义为函数.
您可以改为以中间格式定义propTypes,从中生成propTypes
静态格式.
var myPropTypes = {
color: {
type: 'oneOf',
value: ['green', 'blue', 'yellow'],
},
};
function processPropTypes(propTypes) {
var output = {};
for (var key in propTypes) {
if (propTypes.hasOwnProperty(key)) {
// Note that this does not support nested propTypes validation
// (arrayOf, objectOf, oneOfType and shape)
// You'd have to create special cases for those
output[key] = React.PropTypes[propTypes[key].type](propTypes[key].value);
}
}
return output;
}
var MyComponent = React.createClass({
propTypes: processPropTypes(myPropTypes),
static: {
myPropTypes: myPropTypes,
},
});
然后,您可以通过MyComponent.myPropTypes
或访问自定义propTypes格式element.type.myPropTypes
.
这是帮助这个过程变得更容易的帮手.
function applyPropTypes(myPropTypes, Component) {
Component.propTypes = processPropTypes(myPropTypes);
Component.myPropTypes = propTypes;
}
applyPropTypes(myPropTypes, MyComponent);