Vit*_*man 15 javascript ecmascript-6 reactjs
我想强制用户使用PropTypes 将es6 Map对象传递给React组件,例如:
static propTypes = {
elementsMap: React.PropTypes.map(React.PropTypes.string, editorPropTypes.element).isRequired,
}
Run Code Online (Sandbox Code Playgroud)
但看起来在React中没有这样的东西.(官方文件).
dan*_*y74 16
elementsMap: p.instanceOf(Map).isRequired
Run Code Online (Sandbox Code Playgroud)
它不方便,但可以编写自己的PropType.
来自React的源代码(不幸的是,此时不会公开):
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
Run Code Online (Sandbox Code Playgroud)
您可以这样使用:
const map = createChainableTypeChecker(function(props, propName, componentName, location, propFullName) {
if (...) {
return null; // pass the check
}
return new Error('Error message'); // fail the check
});
Run Code Online (Sandbox Code Playgroud)