简体   繁体   中英

Use react proptypes for validation in purely functional code

I really like the idea of react proptypes and am wondering if they can be used to validate the input of any given function, not just the props being passed to a react component.

For example:

function doSomething (thing1, thing2) {
    Proptypes.validate(arguments, [Proptypes.string, Proptypes.number]);
}

Is there a way of getting proptypes to do this?

Thanks!

Yes they can although you'll need to pass some extraneous params.

You'd probably want to do a wrapper function to make life easier but, don't forget that the React.PropTypes are just functions themselves.

For example:

React.PropTypes.string(props, propName, componentName)

Where props is the entire props object for a component, propName is the name (and key) of the prop being checked, and componentName is the name of the component you're calling it from.

Although I think it would probably be better to roll your own as it would be a very small amount of code to do this yourself and it would shield you against any potential changes to how React.PropTypes work in future versions of React.

Prop validators are functions, so you can just call them. As the customProp example in the Prop Validation doc illustrates, the arguments are props , propName , and componentName . The function returns null on success or an Error on failure. For example:

React.PropTypes.number({'a': 4}, 'a', 'foo')
// null

React.PropTypes.number({'a': 'b'}, 'a', 'foo')
// Error: Invalid undefined `a` of type `string`
// supplied to `foo`, expected `number`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM