记住版本15.5之后,React.PropTypes已经被移除到其他包中,请使用prop-types库
这里是代码变更记录 a codemod script

随着你的APP规模的增长,在类型检查方面会发现越来越多的bug。对有些应用来说,你可以使用js扩展来检查类型,比如flow和typescript。但是,即使你不适用这些,react也有类型检查的能力。为了能使对组件类型检查可用,你得分配额外的propsTypes属性。

  1. import PropTypes from 'prop-types';
  2. class Greeting extends React.Component {
  3. render() {
  4. return (
  5. <h1>Hello, {this.props.name}</h1>
  6. );
  7. }
  8. }
  9. Greeting.propTypes = {
  10. name: PropTypes.string
  11. };

PropTypes输出一组校验器来保证接收到的数据是可用的。在这个例子中,我们使用PropTypes.string。当一个不合法的值作为props传入时,在控制台中会产生警告,性能上的一些原因,propTypes只用在开发模式。

PropTypes

这个例子列出了所提供的不同的校验器:

  1. import PropTypes from 'prop-types';
  2. MyComponent.propTypes = {
  3. // You can declare that a prop is a specific JS type. By default, these
  4. // are all optional.
  5. optionalArray: PropTypes.array,
  6. optionalBool: PropTypes.bool,
  7. optionalFunc: PropTypes.func,
  8. optionalNumber: PropTypes.number,
  9. optionalObject: PropTypes.object,
  10. optionalString: PropTypes.string,
  11. optionalSymbol: PropTypes.symbol,
  12. // Anything that can be rendered: numbers, strings, elements or an array
  13. // (or fragment) containing these types.
  14. optionalNode: PropTypes.node,
  15. // A React element.
  16. optionalElement: PropTypes.element,
  17. // You can also declare that a prop is an instance of a class. This uses
  18. // JS's instanceof operator.
  19. optionalMessage: PropTypes.instanceOf(Message),
  20. // You can ensure that your prop is limited to specific values by treating
  21. // it as an enum.
  22. optionalEnum: PropTypes.oneOf(['News', 'Photos']),
  23. // An object that could be one of many types
  24. optionalUnion: PropTypes.oneOfType([
  25. PropTypes.string,
  26. PropTypes.number,
  27. PropTypes.instanceOf(Message)
  28. ]),
  29. // An array of a certain type
  30. optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
  31. // An object with property values of a certain type
  32. optionalObjectOf: PropTypes.objectOf(PropTypes.number),
  33. // An object taking on a particular shape
  34. optionalObjectWithShape: PropTypes.shape({
  35. color: PropTypes.string,
  36. fontSize: PropTypes.number
  37. }),
  38. // You can chain any of the above with `isRequired` to make sure a warning
  39. // is shown if the prop isn't provided.
  40. requiredFunc: PropTypes.func.isRequired,
  41. // A value of any data type
  42. requiredAny: PropTypes.any.isRequired,
  43. // You can also specify a custom validator. It should return an Error
  44. // object if the validation fails. Don't `console.warn` or throw, as this
  45. // won't work inside `oneOfType`.
  46. customProp: function(props, propName, componentName) {
  47. if (!/matchme/.test(props[propName])) {
  48. return new Error(
  49. 'Invalid prop `' + propName + '` supplied to' +
  50. ' `' + componentName + '`. Validation failed.'
  51. );
  52. }
  53. },
  54. // You can also supply a custom validator to `arrayOf` and `objectOf`.
  55. // It should return an Error object if the validation fails. The validator
  56. // will be called for each key in the array or object. The first two
  57. // arguments of the validator are the array or object itself, and the
  58. // current item's key.
  59. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
  60. if (!/matchme/.test(propValue[key])) {
  61. return new Error(
  62. 'Invalid prop `' + propFullName + '` supplied to' +
  63. ' `' + componentName + '`. Validation failed.'
  64. );
  65. }
  66. })
  67. };

需要单独的子元素

PropTypes.element可用描述出仅仅一个子元素的被传递的需求。

  1. import PropTypes from 'prop-types';
  2. class MyComponent extends React.Component {
  3. render() {
  4. // This must be exactly one element or it will warn.
  5. const children = this.props.children;
  6. return (
  7. <div>
  8. {children}
  9. </div>
  10. );
  11. }
  12. }
  13. MyComponent.propTypes = {
  14. children: PropTypes.element.isRequired
  15. };

默认Props值

通过分配属性defaultProps,你可以定义props的默认值:

  1. class Greeting extends React.Component {
  2. render() {
  3. return (
  4. <h1>Hello, {this.props.name}</h1>
  5. );
  6. }
  7. }
  8. // Specifies the default values for props:
  9. Greeting.defaultProps = {
  10. name: 'Stranger'
  11. };
  12. // Renders "Hello, Stranger":
  13. ReactDOM.render(
  14. <Greeting />,
  15. document.getElementById('example')
  16. );

如果你使用Babel转换器比如transform-class-properties ,你也能使用static属性声明defaultProps。这种语法还没有最终定型而且需要在浏览器工作之前转换。详见class fields proposal

  1. class Greeting extends React.Component {
  2. static defaultProps = {
  3. name: 'stranger'
  4. }
  5. render() {
  6. return (
  7. <div>Hello, {this.props.name}</div>
  8. )
  9. }
  10. }

defaultProps将用于保证this.props.name在没有从父组件分配值的时候,拥有一个默认值。propType检查发生在defaultProps之后,所以,类型检查也用于defaultProps。

官网文章 Advanced Guides :Typechecking With PropTypes