代码之家  ›  专栏  ›  技术社区  ›  Vladimir Humeniuk

如果道具具有动态名称,则使用道具类型验证道具

  •  0
  • Vladimir Humeniuk  · 技术社区  · 6 年前

    在我的react应用程序中,我有一个组件,我在其中传递道具。道具可以有不同的名字。我想用proptype(应该是 PropTypes.oneOfType([PropTypes.number, PropTypes.object] )我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  0
  •   bamse    6 年前

    请看一下这些道具 validating examples.

    您可以编写与示例类似的自定义验证器:

    // 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(
          'Invalid prop `' + propName + '` supplied to' +
          ' `' + componentName + '`. Validation failed.'
        );
      }
    }
    

    希望有帮助!

    推荐文章