es6(弱)映射集的右反应组件PropTypes

时间:2016-03-29 09:05:55

标签: javascript reactjs ecmascript-6

我想强制用户使用PropTypes将es6 Map object传递给React组件,例如:

dd/MM/yy

但看起来在React中没有这样的东西。 (The official documentation)。

3 个答案:

答案 0 :(得分:14)

elementsMap: p.instanceOf(Map).isRequired

答案 1 :(得分:5)

不方便,但可以编写自己的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
});

答案 2 :(得分:2)

尝试使用自定义属性验证程序功能(来自documentation):

// 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...
    },
};