Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - At least one required prop in React

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

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

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?

question from:https://stackoverflow.com/questions/42284076/at-least-one-required-prop-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

from the react docs:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...