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


我想强迫用户通过 es6地图对象 使用PropTypes的React组件,例如:

static propTypes = {
  elementsMap: React.PropTypes.map(React.PropTypes.string, editorPropTypes.element).isRequired,
}

但看起来在React中没有这样的东西。 (官方文件)。


2708
2018-03-29 09:05


起源



答案:


elementsMap: p.instanceOf(Map).isRequired

8
2018-06-09 11:02



但是集合元素的类型呢?就像我们可以用阵列道具一样 arrayProp: PropTypes.arrayOf(PropType.string) - Oleh


答案:


elementsMap: p.instanceOf(Map).isRequired

8
2018-06-09 11:02



但是集合元素的类型呢?就像我们可以用阵列道具一样 arrayProp: PropTypes.arrayOf(PropType.string) - Oleh


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

4
2018-03-29 09:15





尝试使用自定义属性验证器功能(来自 文件):

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

2
2018-03-29 13:21



我如何指定这些例子的数组,或者在这个proptype里面指定一个PropTypes.Shape? - Vitalik Zaidman
将该函数存储为变量(例如 MyPropTypes.mapRequired)并且只是使用 MyPropTypes.mapRequired 无论你在哪里使用任何其他道具类型 PropType.string。 - Brandon