React:propTypes

React.PropTypes has moved into a different package since React v15.5. Please use the prop-types library instead.

在React中,随着项目复杂度的增加,我们难免会遇到一些和类型相关的bug。React提供了一套用于类型检测(针对组件的props)的工具,并在版本15.5之后独立出来作为插件,只在开发模式下使用。因此我们可以不需要用到flow或typescript这类JS扩展语言。

 1 import PropTypes from 'prop-types';
 2 
 3 class Greeting extends React.Component {
 4   render() {
 5     return (
 6       <h1>Hello, {this.props.name}</h1>
 7     );
 8   }
 9 }
10 //定义完组件之后,对其propTypes进行设置。
11 Greeting.propTypes = {
12   name: PropTypes.string
13 };

常见的类型:

 1 MyComponent.propTypes = {
 2   // You can declare that a prop is a specific JS primitive. By default, these
 3   // are all optional.
 4   optionalArray: PropTypes.array,
 5   optionalBool: PropTypes.bool,
 6   optionalFunc: PropTypes.func,
 7   optionalNumber: PropTypes.number,
 8   optionalObject: PropTypes.object,
 9   optionalString: PropTypes.string,
10   optionalSymbol: PropTypes.symbol,
11 
12   // Anything that can be rendered: numbers, strings, elements or an array
13   // (or fragment) containing these types.
14   optionalNode: PropTypes.node,
15 
16   // A React element.
17   optionalElement: PropTypes.element,
18 
19   // You can also declare that a prop is an instance of a class. This uses
20   // JS's instanceof operator.
21   optionalMessage: PropTypes.instanceOf(Message),
22   //...
23 }

更多的类型在:https://facebook.github.io/react/docs/typechecking-with-proptypes.html#proptypes

设置默认值:

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

这部分没什么好讲的。我们引入propTypes后,可以给自定义类的.propTypes赋值,这个值是一个对象形式的校验器,里面对类的props的各个属性设置了有效类型。之后如果我们传入的值不是有效类型,则控制台会发出警告,帮助我们避免类型错误。

原文地址:https://www.cnblogs.com/alan2kat/p/7476930.html