react中组件传递数据使用props

props的深入了解

1.props的children属性

  • children属性:表示组件标签的子节点,当组件标签有子节点时,props就会有该属性
  • children属性和普通的props一样,可以是任意值(文本,react,元素,组件,甚至是函数)
  • 注:当前组件包含内容的情况下,在render方法中return回去的组件不会包含在内
props的children属性
const App=(props)=>{
    console.log(props);
    
    return (
        <div>
            props的children属性
            {props.children}
        </div>
    )
}
ReactDOM.render(<App>children</App>,document.getElementById("root"))

 2.props校验

  • 允许在创建组件的时候,指定props的类型,格式等
  • 作用:捕获使用组件时因为props导致的错误,给出明确的错误提示,增加组件的健壮性
  • 需要用到prop-types这个第三方的包进行实现

使用prop-types包步骤

1.在终端中安装 yarn add prop-types或者 npm i prop-types

2.在文件进行导入 import PropTypes from ‘prop-types’

3.使用  组件名.propTypes={

          验证的属性名:PropTypes.类型

}

// /导入prop-types
import PropTypes from 'prop-types'
const App=(props)=>{
    const arr=props.colors
    const lis=arr.map((item,index)=><li key={index}>{item}</li>)
    return (
        <div>
            <ul>
            {lis}
            </ul>
            
        </div>
        
    )
}
// 使用prop-types添加属性的校验规则
App.propTypes={
    colors:PropTypes.array
}
ReactDOM.render(<App colors={['red','blue']}/>,document.getElementById("root"))

props校验规则

1.创建类型:array,bool,func,number,object,string

2.React元素类型:element

3.必填项:isRequired

特定的结构对象:shape({})验证规则可以写多个,作为对象进行传递

import PropTypes from 'prop-types'

const App = props => {
  return (
    <div>
      <h1>props校验:</h1>
    </div>
  )
}

// 添加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中的area的验证规则和price的验证规则
  filter: PropTypes.shape({
    area: PropTypes.string,
    price: PropTypes.number
  })
}

ReactDOM.render(<App fn={() => {}} />, document.getElementById('root'))

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值