当前位置:   article > 正文

【React】8 props的children、校验、默认值_react 判断子元素是 react元素

react 判断子元素是 react元素

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 />)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

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

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"} />)}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

效果:
传入错误参数时,会提示类型错误
在这里插入图片描述
常用验证规则:
若是必填则后面加.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.'
      );
    }
  })
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95

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>
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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

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

  }
}
// 默认值的第二种,指定 props 的默认值,这个方法会一直生效
Age.defaultProps = {
    name:18
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/297612
推荐阅读
相关标签
  

闽ICP备14008679号