【React】8 props的children、校验、默认值

【React】8 props的children、校验、默认值

1. props.children 属性

  • children 属性:表示组件标签的子节点。当组件标签有子节点时,props就会有该属性。
  • chidren 属性与普通的props一样,值可以是任意值(文本、React元素、组件,甚至是函数)

demo:

import React from 'react'
import ReactDOM from 'react-dom/client'


//组件1
class  User extends React.Component {


  render() {
    return (
      // 传入非函数children
      // <Node1>hello</Node1>
      // <Node1><button>hello</button></Node1>

      //传入函数children
      <Node1>{
        () => console.log("函数1")
      }</Node1>
    )
  }
}


//组件
const Node1 = (props) => {

  //使用函数children
  props.children()
  return (
    //使用非函数children
    // <div>node1--{props.children}</div>

    <div>node1--</div>
  )
}


const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<User />)

效果:
在这里插入图片描述

2. props 校验

使用步骡

  1. 安装包 prop-types ( yarn add prop-types / npm i prop-types )
  2. 导入 prop-types包,import PropTypes from 'prop-types'
  3. 使用组件名.propTypes ={} 来给组件的props添加校验规则
  4. 按验规见面过 PropTypes象来指定
import React from 'react'
import ReactDOM from 'react-dom/client'
//导入校验包
import PropTypes from 'prop-types'

//组件
const Node1 = (props) => {
  console.log(props)
  return (
    <div>node1--{props.colors[0]}</div>
  )
}

//添加校验规则
Node1.propTypes = {
  colors: PropTypes.array
}

const root = ReactDOM.createRoot(document.getElementById("root"))
// root.render(<Node1 colors={["red", "blue"]} />)
root.render(<Node1 colors={"qq"} />)}

效果:
传入错误参数时,会提示类型错误
在这里插入图片描述
常用验证规则:
若是必填则后面加.isRequired

MyComponent.propTypes = {
  // You can declare that a prop is a specific JS primitive. By default, these
  // are all optional.
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,
 
  // Anything that can be rendered: numbers, strings, elements or an array
  // (or fragment) containing these types.
//验证是否为节点
  optionalNode: PropTypes.node,
 
//验证是否为元素
  // A React element (ie. <MyComponent />).
  optionalElement: PropTypes.element,
 
//验证是否为元素类型
  // A React element type (ie. MyComponent).
  optionalElementType: PropTypes.elementType,
 
//验证是否为另一个类的实例
  // You can also declare that a prop is an instance of a class. This uses
  // JS's instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),
 
//验证传入值是否在给定范围
  // You can ensure that your prop is limited to specific values by treating
  // it as an enum.
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),
 
//验证传入类型是否在给定范围
  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),
 
  // An array of a certain type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
 
  // An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),
 
  // You can chain any of the above with `isRequired` to make sure a warning
  // is shown if the prop isn't provided.
 
  // An object taking on a particular shape
  optionalObjectWithShape: PropTypes.shape({
    optionalProperty: PropTypes.string,
    requiredProperty: PropTypes.number.isRequired
  }),
 
  // An object with warnings on extra properties
  optionalObjectWithStrictShape: PropTypes.exact({
    optionalProperty: PropTypes.string,
    requiredProperty: PropTypes.number.isRequired
  }),
 
  requiredFunc: PropTypes.func.isRequired,
 
  // A value of any data type
  requiredAny: PropTypes.any.isRequired,
 
  // You can also specify a custom validator. It should return an Error
  // object if the validation fails. Don't `console.warn` or throw, as this
  // won't work inside `oneOfType`.
//回调函数:自定义验证规则
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },
 
  // You can also supply a custom validator to `arrayOf` and `objectOf`.
  // It should return an Error object if the validation fails. The validator
  // will be called for each key in the array or object. The first two
  // arguments of the validator are the array or object itself, and the
  // current item's key.
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};

3. props默认值

指定 props 的默认值, 这个方法只有浏览器编译以后才会生效

class HandsomeBoy extends Component{
  // 设置默认值
  //defaultProps 可以为 Class 组件添加默认 props,基于 static 的写法
  static defaultProps = {
    name:'pyq'
  }
  constructor(props){
    super(props)
  }
  render(){
  return <section>{this.props.name}</section>
  }
}

指定 props 的默认值,这个方法会一直生效

class Age extends Component{
  
  render(){
    return <section>{this.props.name}</section>

  }
}
// 默认值的第二种,指定 props 的默认值,这个方法会一直生效
Age.defaultProps = {
    name:18
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值