react学习—属性默认值和类型验证

一、属性默认值

通过一个静态属性defaultProps告知react属性默认值

1、函数组件属性默认值

//FuncDefault.js
import React from 'react'

export default function FuncDefault(props) {
  return (
    <div>
      a: { props.a },b: { props.b },c: { props.c }
    </div>
  )
}
//属性默认值
FuncDefault.defaultProps = {
  a: 1,
  b: 2,
  c: 3
}
import React, { Component } from 'react'
import FuncDefault from './FuncDefault'

export default class Input extends Component {
  render() {
    return (
      <div>
        {/* 注意我们没有传入属性值哦 */}
        <FuncDefault />
      </div>
    )
  }
}

然后组件就会默认调用我们设置的默认属性值。
在这里插入图片描述
如果我们又传入属性值,有设置默认属性值呢?

import React from 'react'

export default function FuncDefault(props) {
  console.log(props);// 给函数组件之前,props已经与defaultProps完成了混合
  return (
    <div>
      a: { props.a },b: { props.b },c: { props.c }
    </div>
  )
}
//属性默认值
FuncDefault.defaultProps = {
  a: 1,
  b: 2,
  c: 3
}

在这里插入图片描述

2、类组件默认属性值

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

export default class ClassDefault extends Component {
  // he函数组件一样,在调用组件时props已经混合完成
  constructor(props) {
    console.log(props);
    super(props);
  }
  render() {
    return (
      <div>
        a: { this.props.a},b: { this.props.b},c: { this.props.c}
      </div>
    )
  }
}
ClassDefault.defaultProps = {
  a: 1,
  b: 2,
  c: 3
}
import React, { Component } from 'react'
import ClassDefault from './ClassDefault'

export default class Input extends Component {
  render() {
    return (
      <div>
        {/* 注意我们没有传入属性值哦 */}
        <ClassDefault a={4} b={5} />
      </div>
    )
  }
}

在这里插入图片描述
此外,类组件的默认属性值,也可以直接使用静态成员的方式书写。

export default class ClassDefault extends Component {
  // he函数组件一样,在调用组件时props已经混合完成
  constructor(props) {
    console.log(props);
    super(props);
  }
  static defaultProps = {
    a: 1,
    b: 2,
    c: 3
  }
  render() {
    return (
      <div>
        a: { this.props.a},b: { this.props.b},c: { this.props.c}
      </div>
    )
  }
}

二、属性类型验证

使用库:prop-types

对组件使用静态属性propTypes告知react如何检查属性

1、常见值类型

// ValidationComp.js
import React, { Component } from 'react'
import PropTypes from 'prop-types';

export default class ValidationComp extends Component {
  static propTypes = {
    a: PropTypes.number,
    b: PropTypes.bool
  }
  render() {
    return (
      <div>
        a: { this.props.a },b: { this.props.b }
      </div>
    )
  }
}
import React, { Component } from 'react'
import ValidationComp from './ValidationComp'

export default class Input extends Component {
  render() {
    return (
      <div>
        <ValidationComp a={4} b={'true'} />
      </div>
    )
  }
}

由于我们b属性开启了类型验证为布尔,此时我们传入的是字符,虽然页面上成功显示,单控制台会进行报错。
在这里插入图片描述
也可以使用jsx语法,直接传入b即可,默认为true。

import React, { Component } from 'react'
import ValidationComp from './ValidationComp'

export default class Input extends Component {
  render() {
    return (
      <div>
        {/* 注意我们没有传入属性值哦 */}
        <ValidationComp a={4} b />
      </div>
    )
  }
}

也可以不传入b值,使用属性默认值。

export default class ValidationComp extends Component {
  static defaultProps = {
    b: false
  }
  static propTypes = {
    a: PropTypes.number,
    b: PropTypes.bool
  }
  render() {
    return (
      <div>
        a: { this.props.a },b: { this.props.b }
      </div>
    )
  }
}

通过这里我们也可以发现,仍然是在调用组件时,属性值和默认属性值已经完成混合,所以此时属性类型验证才能知道b的值类型为布尔
在这里插入图片描述

2、是否必传isRequired

在之前的学习中我们知道,哪怕我么适应了b属性值,但b属性值不传不设置默认值,react不会有报错提示。

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

export default class ValidationComp extends Component {
  // static defaultProps = {
  //   b: false
  // }
  // static propTypes = {
  //   a: PropTypes.number,
  //   b: PropTypes.bool
  // }
  render() {
    return (
      <div>
        a: { this.props.a },b: { this.props.b }
      </div>
    )
  }
}

一旦我们对属性类型验证开启必传验证后。

export default class ValidationComp extends Component {
  // static defaultProps = {
  //   b: false
  // }
  static propTypes = {
    a: PropTypes.number,
    b: PropTypes.bool.isRequired
  }
  render() {
    return (
      <div>
        a: { this.props.a },b: { this.props.b }
      </div>
    )
  }
}

此时系统会进行提示报错,b必须传入。
在这里插入图片描述

3、其它类型验证

由于react的验证方法很多,但是常用的往往就那几个,剩下的就不再一一详细举例了。
博主直接将其他的验证方法直接附上。

import React, { Component } from 'react'
import PropTypes from 'prop-types'
export class A {}

export default class ValidationComp extends Component {
  static defaultProps = {
    b: false
  }
  static propTypes = {
    a: PropTypes.number.isRequired,  //a属性必须是一个数字类型,并且必填
    b: PropTypes.bool.isRequired, //b必须是一个bool属性,并且必填
    onClick: PropTypes.func, //onClick必须是一个函数
    c: PropTypes.any, //1. 可以设置必填   2. 阵型保持整齐(所有属性都在该对象中)
    d: PropTypes.node.isRequired, //d必填,而且必须是一个可以渲染的内容,字符串、数字、React元素   d={<Comp />}
    e: PropTypes.element, //e必须是一个React元素  e={<Comp />}
    F: PropTypes.elementType, //F必须是一个组件类型  F={Comp}
    g: PropTypes.instanceOf(A), //g必须是A的实例,普通对象也不行  g={new A}
    sex: PropTypes.oneOf(["男", "女"]), //属性必须是数组当中的一个,非'男'即'女'  sex={'男'}
    h: PropTypes.arrayOf(PropTypes.number), //数组的每一项必须满足类型要求(可以使空数组)  n={[1,2,3]}
    i: PropTypes.objectOf(PropTypes.number), //每一个属性必须满足类型要求  i={{a: 1}}
    j: PropTypes.shape({ //属性必须满足该对象的要求,相当于组合使用
      name: PropTypes.string.isRequired, //name必须是一个字符串,必填
      age: PropTypes.number, //age必须是一个数字
      address: PropTypes.shape({// 如果继续嵌套函数,别忘了用shape
        province: PropTypes.string,
        city: PropTypes.string
      })
    }),
    k: PropTypes.arrayOf(PropTypes.shape({// 如果想验证数组每一个元素,可以灵活嵌套使用
      name: PropTypes.string.isRequired,
      age: PropTypes.number.isRequired
    })),
    l: PropTypes.exact({...}),// 对象必须精确匹配传递的数据,不能设置无效验证且不传属性
    m: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),// 数组元素的类型必须为其中一个,和oneOf类似
  }
  render() {
    return (
      <div>
        a: { this.props.a },b: { this.props.b }
      </div>
    )
  }
}

4、自定义验证

如果以上验证方法仍不能对你的属性进行验证,也可以自定义验证。
自定义属性检查,如果有错误,返回错误对象即可

// ValidationComp.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'

export default class ValidationComp extends Component {
  static defaultProps = {
    b: false
  }
  static propTypes = {
    a: PropTypes.number.isRequired,  //a属性必须是一个数字类型,并且必填
    b: PropTypes.bool, //b必须是一个bool属性,并且必填
    fn: function (props, propName, componentName) {
      console.log(props, propName, componentName);
      const val = props[propName];
      if(typeof val === 'string'){
        return new Error(`invalid prop ${propName} in ${componentName}${propName} is String`);
      }
    }
  }
  render() {
    return (
      <div>
        a: { this.props.a },b: { this.props.b },fn: { this.props.fn }
      </div>
    )
  }
}
import React, { Component } from 'react'
import ValidationComp from './ValidationComp'

export default class Input extends Component {
  render() {
    return (
      <div>
        <ValidationComp a={4} b={true} fn={'自定义验证'} />
      </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、付费专栏及课程。

余额充值