我想强迫用户通过 es6地图对象 使用PropTypes的React组件,例如:
static propTypes = {
elementsMap: React.PropTypes.map(React.PropTypes.string, editorPropTypes.element).isRequired,
}
但看起来在React中没有这样的东西。 (官方文件)。
我想强迫用户通过 es6地图对象 使用PropTypes的React组件,例如:
static propTypes = {
elementsMap: React.PropTypes.map(React.PropTypes.string, editorPropTypes.element).isRequired,
}
但看起来在React中没有这样的东西。 (官方文件)。
elementsMap: p.instanceOf(Map).isRequired
elementsMap: p.instanceOf(Map).isRequired
这不方便,但可以编写自己的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;
}
您可以这样使用:
const map = createChainableTypeChecker(function(props, propName, componentName, location, propFullName) {
if (...) {
return null; // pass the check
}
return new Error('Error message'); // fail the check
});
尝试使用自定义属性验证器功能(来自 文件):
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error('Validation failed!');
}
}
所以这可能看起来像:
static propTypes = {
elementMap: (props, propName) => {
const m = props[propName];
if (!m) { return new Error(`Required property ${propName} not supplied`); }
if (!(m instanceof Map)) { return new Error("must be a Map"); }
// check contents of map if you want...
},
};