react 的children属性和vue的插槽一样,props的验证,props的默认值 - 前端笔记-1.children属性 children属性和vue的插槽一样可以直接写在 组件之间 在组件内通过 this....

学习笔记

点滴记忆
回忆过往
首页>> web前端 >>react 的children属性和vue的插槽一样,props的验证,props的默认值 - 前端笔记
1.children属性
    children属性和vue的插槽一样可以直接写在  组件之间
        在组件内通过  this.children获取  数据
class App extends React.Component {
  state = {
    msg'我是app'
  }
  render () {
    return
    <Dbs>我是children属性</Dbs>

  }
}

class Dbs extends React.Component {
  render () {
    return <div>{this.children}</div>
  }
}


2.props的验证
    props的验证要通过一个外部插件实现
    对于组件来说,props是外来的,无法保证组件使用者传入什么格式的数据,简单来说就是组件调用者可能不知道组件封装着需要什么样的数据
  • 安装包 prop-types (yarn add prop-types | npm i props-types)

  • 导入prop-types 包

  • 使用组件名.propTypes={} 来给组件的props添加校验规则

  • 校验规则通过PropTypes对象来指定

import React from "react";
import PropsTypes from 'prop-types'

function App (props) {
  return (
    <h1>我是{props.col}</h1>
  )
}

// 监听App组件的 col值结果必须是array 不然就报错
App.propTypes = {
  colPropsTypes.array
}


3.props的默认值
import React from "react";
import PropsTypes from 'prop-types'

function App (props) {
  return (
    <h1>我是{props.col}</h1>
  )
}

// 监听App组件的 col值结果必须是array 不然就报错
App.propTypes = {
  colPropsTypes.array
}

// 默认值
App.defaultProps = {
  col: [123]
}



×

感谢您的支持,我们会一直保持!

扫码支持
请土豪扫码随意打赏

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

打赏作者
版权所有,转载注意明处:前端笔记 » react 的children属性和vue的插槽一样,props的验证,props的默认值

网友评论(0)