React 中至少需要一个道具 [英] At least one required prop in React

查看:114
本文介绍了React 中至少需要一个道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to make at least one of the props required:

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

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

So in the example above, either data or url prop must be provided. The use case here is that the user could either provide the data or the url. If the url is provided, then the component will fetch the data.

额外问题:我如何做至少一个道具与只做一个道具?

Bonus question: How do I do at least one prop vs only one of the props?

推荐答案

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

PropTypes actually can take a custom function as an argument so you could do something like this:

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

which allows for customer Error messaging. You can only return null or an Error when using this method

你可以在这里找到更多信息

You can find more info on that here

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

这篇关于React 中至少需要一个道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆