React中至少需要一个道具

时间:2017-02-16 20:35:03

标签: javascript reactjs

我需要制作至少一个所需的道具:

MyComponent.propTypes = {
   data: PropTypes.object,
   url: PropTypes.string
};

因此,在上面的示例中,必须提供dataurl道具。这里的用例是用户可以提供dataurl。如果提供了url,则该组件将获取data

奖金问题:我如何做至少一个道具与仅有一个道具?

5 个答案:

答案 0 :(得分:27)

PropTypes实际上可以将自定义函数作为参数,因此您可以执行以下操作:

MyComponent.propTypes = {
  data: (props, propName, componentName) => {
    if (!props.data && !props.url) {
      return new Error(`One of props 'data' or 'url' was not specified in '${componentName}'.`);
    }
  },

  url: (props, propName, componentName) => {
    if (!props.data && !props.url) {
      return new Error(`One of props 'url' or 'data' was not specified in '${componentName}'.`);
    }
  }
}

允许客户错误消息传递。使用此方法时,您只能返回null或Error

您可以在此处找到更多相关信息

https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes

来自反应文档:

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

答案 1 :(得分:13)

@ finalfreq解决方案的更简洁版本:

const requiredPropsCheck = (props, propName, componentName) => {
  if (!props.data && !props.url) {
    return new Error(`One of 'data' or 'url' is required by '${componentName}' component.`)
  }
}

Markdown.propTypes = {
  data: requiredPropsCheck,
  url: requiredPropsCheck,
}

答案 2 :(得分:2)

finalfreq answer顶部添加并与对其进行kousha评论有关。

我有一个需要图标或标题的按钮组件。确保上面的答案中至少有一个像这样,然后可以像这样验证其类型:

Button.propTypes = {
  icon: (props, propName, componentName) => {
    if (!props.icon && !props.title) {
      return new Error(`One of props 'icon' or 'title' was not specified in '${componentName}'.`)
    }
    if (props.icon) {
      PropTypes.checkPropTypes({
        icon: PropTypes.string, // or any other PropTypes you want
      },
      { icon: props.icon },
      'prop',
      'PrimaryButtonWithoutTheme')
    }
    return null
  }
  title: // same process
}

有关PropTypes.checkPropTypes的更多信息,请阅读here

答案 3 :(得分:0)

我写了这个助手来以可重复使用的方式解决相同的问题。您可以像propType函数一样使用它:

MyComponent.propTypes = {
  normalProp: PropType.string.isRequired,

  foo: requireOneOf({
    foo: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    bar: PropTypes.string,
  }, true),
};

,在此示例中,它确保foo或bar中的一个位于MyComponent道具中。如果省略第二个参数,它将确保仅传递foo或bar中的一个。

/**
 * Takes a propTypes object ensuring that at least one of the passed types
 * exists on the component.
 *
 * Usage:
 *
 * MyComponent.propTypes = {
 *   normalProp: PropType.string.isRequired,
 *
 *   foo: requireOneOf({
 *     foo: PropTypes.oneOfType([
 *       PropTypes.string,
 *       PropTypes.number
 *     ]),
 *     bar: PropTypes.string,
 *   }, true),
 * };
 *
 * @param requiredProps object
 * @param allowMultiple bool = false  If true multiple props may be
 *                                    passed to the component
 * @return {Function(props, propName, componentName, location)}
 */
export const requireOneOf = (requiredProps, allowMultiple = false) => {
  return (props, propName, componentName, location) => {
    let found = false;

    for (let requiredPropName in requiredProps) {
      if (requiredProps.hasOwnProperty(requiredPropName)) {
        // Does the prop exist?
        if (props[requiredPropName] !== undefined) {
          if (!allowMultiple && found) {
            return new Error(
              `Props ${found} and ${requiredPropName} were both passed to ${componentName}`
            );
          }

          const singleRequiredProp = {};
          singleRequiredProp[requiredPropName] = requiredProps[requiredPropName];
          const singleProp = {};
          singleProp[requiredPropName] = props[requiredPropName];

          // Does the prop match the type?
          try {
            PropTypes.checkPropTypes(singleRequiredProp, singleProp, location, componentName);
          } catch (e) {
            return e;
          }
          found = requiredPropName;
        }
      }
    }

    if (found === false) {
      const propNames = Object.keys(requiredProps).join('", "');
      return new Error(
        `One of "${propNames}" is required in ${componentName}`
      );
    }
  };
};

答案 4 :(得分:0)

   
function requireALeastOne(checkProps) {
  return function(props, propName, compName) {
    const requirePropNames = Object.keys(checkProps);

    const found = requirePropNames.find((propRequired) => props[propRequired]);

    try {
      if (!found) {
        throw new Error(
          `One of ${requirePropNames.join(',')} is required by '${compName}' component.`,
        );
      }
      PropTypes.checkPropTypes(checkProps, props, propName, compName);
    } catch (e) {
      return e;
    }
    return null;
  };
}


const requireALeast = requireALeastOne({
  prop1: PropTypes.string,
  prop2: PropTypes.number
});

Comp.propTypes = {
  prop1: requireALeast,
  prop2: requireALeast
};

相关问题