React——传值的校验和默认值

1、传值的校验

  • 引入 prop-types
import PropTypes from 'prop-types'
  • propTypes 进行设置 (注意是 小写p 开头,和包名的 大写P 开头不一样)
// 单类型校验
[组件名].propTypes = {
  [键名]: PropTypes.[类型]
}

// 组合类型校验
[组件名].propTypes = {
  [键名]: PropTypes.oneOfType( [PropTypes.[类型], ...] )
}

// 必须要传过来的
[组件名].propTypes = {
  [键名]: PropTypes.[类型].isRequired
}
  • Parent.js
import React, {Component, Fragment} from 'react'
import Child from './Child'

class Parent extends Component {
  constructor(props){
    super(props)
    this.state = {
      data: 'parent => child'
    }
  }

  render(){
    return(
      <Fragment>
        <Child data={this.state.data}></Child>
      </Fragment>
    )
  }
}

export default Parent
  • Child.js
import React, {Component, Fragment} from 'react'
import PropTypes from 'prop-types'

class Child extends Component {
  constructor(props){
    super(props)
  }

  render(){
    return(
      <Fragment>
      <div>{this.props.data}</div>
      </Fragment>
    )
  }
}

Child.propTypes = {
  data: PropTypes.string
}

export default Child

  • 校验结果不正确会在控制台报警告,程序依旧能执行
    在这里插入图片描述

2、传值的默认值设置

  • defaultProps 进行设置
[组件名].defaultProps= {
  [键名]: [默认值]
}
  • Child.js
import React, {Component, Fragment} from 'react'

class Child extends Component {
  constructor(props){
    super(props)
  }

  render(){
    return(
      <Fragment>
      <div>{this.props.hello}</div>
      </Fragment>
    )
  }
}

Child.defaultProps = {
  hello: 'hello'
}

export default Child
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值