Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 中的 prop-types #18

Open
GRPdream opened this issue May 24, 2019 · 0 comments
Open

React 中的 prop-types #18

GRPdream opened this issue May 24, 2019 · 0 comments

Comments

@GRPdream
Copy link
Owner

prop-types

propTypes 主要用于对组件之间传递数据的校验,以防止传输的数据类型出错的情况
要使用的话需要下载 prop-types 这个包并引入

一个简单的例子

Son.propTypes = {
  number: PropTypes.number
}

常见的用法

方法 描述
PropTypes.array 检测数组类型
PropTypes.bool 检测布尔类型
PropTypes.func 检测函数(Function类型)
PropTypes.number 检测数字
PropTypes.object 检测对象
PropTypes.string 检测字符串
PropTypes.symbol ES6新增的symbol类型

几个比较特殊的方法

1.PropTypes.oneOfType
这个方法能检测目标值是否在一个合法的范围中

  Son.propTypes = {  //检测一个值是字符或者数字
    number:PropTypes.oneOfType(
      [PropTypes.string,PropTypes.number]
    )
  }

2..PropTypes.oneOf
规定目标必须是后面数组的值之一

      Son.propTypes = {  //规定传入的值必须是数字的12或者13
          number:PropTypes.oneOf(
              [12,13]
          )
    }

3.PropTypes.arrayOf PropTypes.objectOf
用于检测数组内或者对象内的值

  Son.propTypes = {  //数组的值必须为数字
     array:PropTypes.arrayOf(PropTypes.number)
}

4..PropTypes.shape
可以规定对象内多个值的属性,可以理解为3的升级版

  Son.propTypes = {  
     object:PropTypes.shape({  //规定对象内的名字为字符串类型,年龄为数字类型
     name:PropTypes.string,
     age:PropTypes.number
      })
}

5.isRequired
对于有些传入值,我们不仅要求他符合某种类型,还认为他是必需的,这个时候可以使用isRequired

Son.propTypes = {
    number:PropTypes.number.isRequired
}

PS:如果不要求值的具体类型,但他又是必须时,可以使用PropTypes.any.isRequired

6.除了上述情况时,面对更复杂的校验,我们可以把PropTypes写成函数进行校验

  Son.propTypes = {  
     email:function(props,propName,componentName){  //判断邮箱
            if(!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(props[propName])){
                  return new Error('组件' + componentName+ '里的属性' + propName + '不符合邮箱的格式');
                         }
                }
}

参考文档

react prop-types的使用讲解

@GRPdream GRPdream changed the title React 中的 prop-types 与 defaultprops React 中的 prop-types May 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant