react-属性默认值与类型验证

属性默认值

react提供了属性默认值的设置方法
defaultProps

App.js

import React, { Component } from 'react'
import ClassDefault from './components/ClassDefault'

export default class App extends Component {
  render() {
    return (
      <ClassDefault />
    )
  }
}

ClassDefault.js

import React, { Component } from 'react'

export default class ClassDefault extends Component {
  // 类组件可以这样定义属性默认值
  static defaultProps = {
    a: 1,
    b: 2,
    c: 3
  }

  render() {
    return (
      <div>
        a: {this.props.a}
        b: {this.props.b}
        c: {this.props.c}
      </div>
    )
  }
}

// 函数组件和类组件都可以这么写属性默认值
// ClassDefault.defaultProps = {
//   a: 1,
//   b: 2,
//   c: 3
// }

类型验证

需要使用库: prop-types
ps: 安装React会自动安装这个库,不需要额外安装,直接引用就行

对组件使用静态属性propTypes来验证数据

ClassValidate.js

import React, { Component } from 'react'
import PropType from 'prop-types'

export default class ClassValidate extends Component {

  static propTypes = {
    a: PropType.number.isRequired, // 必须是数字且必填,必填属性可以用在任意验证
    b: PropType.string, // 必须是字符串, 可不填
    c: PropType.bool, // 必须是布尔
    d: PropType.any, // 任意类型
    e: PropType.array, // 数组
    f: PropType.object, // 对象
    g: PropType.func, // 函数, 常用于事件
    h: PropType.symbol, // 符号类型
    i: PropType.node, // 可渲染的内容,字符串,数字,React元素
    j: PropType.element, // React元素
    // 需要一个React组件名称 使用时: const AAAA = this.props.k; render() {return (<AAAA />)}
    k: PropType.elementType,
    // l: PropType.instanceOf(构造函数) // 必须是该构造函数的实例
    m: PropType.oneOf([1,2,3]), // 1 2 3其中一个
    n: PropType.oneOfType([PropType.number, PropType.string]), // 类型为数字或字符串
    o: PropType.arrayOf(PropType.number), // 函数中可以传任意类型, 此例表示o是一个数字数组
    p: PropType.objectOf(PropType.array), // 该对象每一个属性值为数组,没啥用其实
    // shape表示传入的对象必须满足该格式,如果传入aa属性则必须为数组,
    // 不传没事,传入的q可以多出属性比如 q: {cc: 1} 不会报错
    q: PropType.shape({
      aa: PropType.number,
      bb: PropType.shape({
        aaa: PropType.string
      })
    }).isRequired, // 加上isRequired表示 aa,bb属性都必传,bb必须为对象
    // 表示r为对象且不能有aa以外的属性,可以不传aa,传入的话必须为数字
    r: PropType.exact({
      aa: PropType.number
    })
  }
  /**
   * 自定义验证放这
   * z: function (props, propName, componentName) {
   *    props表示静态对象propTypes中所有的属性
   *    propName表示属性名 此例为z
   *    componentName表示组件名, 此例为ClassValidate
   * }
   */


  render() {
    return (
      <div>ClassValidate</div>
    )
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

合法的咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值