zoukankan      html  css  js  c++  java
  • 07.React组件进阶(三)Props 深入

    props 校验

    ``` //1.对于组件来说,props是外来的,无法保证组件使用者传入什么格式的数据 //2.如果传入的数据格式不对,可能会导致组件内部报错 //3.关键问题:组件的使用者不知道明确的错误原因 //4.props 校验:允许在创建组件的时候,就指定props的类型,格式等

    App.propTypes = {
    colors:PropTypes.array
    }

    //5.作用:捕获使用组件时因为props 导致的错误,给出明确的错误提示,增加组件的健壮性

    <h3>使用步骤</h3>
    

    1.安装包 prop-types (yarn add prop-types/npm i props-types)
    2.导入 prop-types包
    3.使用 组件名.propTypes = {} 来给组件的props添加校验规则
    4.校验规则 通过PropTypes 对象来指定

    import PropTypes from 'prop-types'

    const App = props =>{
    const arr = props.colors
    const lis = arr.map((item,index)=>

  • {item}
  • )

    return <ul>{lis}</ul>
    

    }
    //添加props校验
    App.propTypes={
    //约定colors属性为array类型
    //如果类型不对,则报出明确错误,便于分析错误原因
    colors:PropTypes.array
    }
    ReactDOM.render(<App colors={['red','blue']}/>,document.getElementById('root'))

    <h2>props 校验-约束规则</h2>
    

    1.常见类型:array, bool, func, number, object, string
    2.React元素类型:element
    3.必填项:isRequied

    //常见类型
    optionalFunc:PropTypes.func

    //必选
    requiredFunc: PropTypes.func.isRequired,

    //特定结构的对象
    optionalObjectWithShape: PropTypes.shape({
    colors: PropTypes.string,
    fontSize:PropTypes.number
    })

    import PropTypes from 'prop-types'

    const App = props =>{
    return(


    props校验:



    )
    }
    //添加props校验
    //属性 a 的类型: 数值(number)
    //属性 fn 的类型: 函数(func)并且为必填项
    //属性 tag 的类型: React元素(element)
    //属性 filter 的类型: 对象({area:‘上海',price:1999})
    App.propTypes={
    a:PropTypes.number,
    fn:PropTypes.func.isRequired,
    tag:PropTypes.element,
    filter:PropTypes.shape({
    area:PropTypes.string,
    price:PropTypes.number
    })
    }
    ReactDOM.render(<App fn={()=>{}}/>,document.getElementById('root'))

    <h2>props 的默认值</h2>
    

    //场景:分页组件-> 每页显示条数
    //作用:给props 设置默认值,在未传入 props时生效
    //(如果由传入,以传入值为准)

    import PropTypes from 'prop-types'

    const App = props =>{
    return(

    此处展示props的默认值:{props.pageSize}

    ) } //添加默认值 App.defaultProps={ pageSize:10 } ReactDOM.render(,document.getElementById('root')) ```
查看全文
  • 相关阅读:
    struts2 spring3 整合
    SilverLight 银光 基础.net 跨网页,桌面软件体验更好,但是要这个插件
    struts 理解 action
    vb 坐标点击
    错误struts2 json There is no Action mapped for namespace
    struts 与 jquery 整合
    springmvc jquery 界面没回应
    css 相关学习
    spring + ehcache 配置
    jquery json 结合
  • 原文地址:https://www.cnblogs.com/foreverLuckyStar/p/12246896.html
  • Copyright © 2011-2022 走看看