• React中Props的使用


    Props使用

    Props的基本使用

    • props传递接受数据

         1.在组件标签上添加属性

          2.类组件使用 this.props 接收数据。函数组件使用参数 props 接收数据。

      • 使用类接收数据
      1. // 类接受 props 数据
      2. class App extends React.Component {
      3. render() {
      4. return (
      5. <div>
      6. <h1>姓名:{this.props.name}</h1>
      7. <h1>年龄:{this.props.age}</h1>
      8. </div>
      9. )
      10. }
      11. }
      12. ReactDOM.render(<App name="Tom" age="18" />, document.getElementById('root'))
      • 使用函数接收数据
      1. // 函数接收 props 数据
      2. const App = props => {
      3. return (
      4. <div>
      5. <h1>姓名:{props.name}</h1>
      6. <h1>年龄:{props.age}</h1>
      7. </div>
      8. )
      9. }
      10. ReactDOM.render(<App name="Tom" age="18" />, document.getElementById('root'))
    • props 特点

      • 可以给组件传递任意类型的数据

      • props 传递的数据是只读的数据。只能读取属性的值,而不能进行修改。

      • 在使用类组件时,若写了构造函数,必须将 props 传给 super()

    1. constructor(props) {
    2. super(props)
    3. ...
    4. }

    Props深入

    • Children属性

      • 表示组件的子节点。有子节点的时候, Props 就会有这个属性

      • 和普通的Props 一样,值可以是任意值

    • Props的校验

      • 对于组件来说 Props 是外来的,无法保证组件的使用者传入的数据格式

      • 传入的数据格式不对的话,会导致组件内部报错,且不知道明确的错误原因

      • Props校验:在创建组件的时候,会指定 Props 的类型和格式---这样就算格式出错也会给出一个明确的错误。

      • 使用步骤:

        • 安装 Props-types(npm i prop-types/yarn add prop-types)

        • 导入prop-types 包

        • 使用 组件名.propType = {} 给组件添加校验规则

    1. ```javascript
    2. import propTypes from 'prop-types'
    3. function App(props) {
    4. return (
    5. <h1>{props.name}</h1>
    6. )
    7. }
    8. App.propTypes = {
    9. name : PropTypes.string
    10. }
    11. ```
    • 约束规则

      • 常见类型: Array、number、object、string、bool、func

      • React 元素类型: element

      • 是否必填:isRequired

      • 特定结构的对象: shape({ }) ----- 约束多个属性的时候,整合到这个对象中一起书写

    • Props的默认值

      • 定义一个默认值,不传入数值的时候,默认采用这个数值
      1. const App = props => {
      2. return (
      3. <div>props.name/div>
      4. )
      5. }
      6. //添加默认值
      7. App.defaultProps = {
      8. name : 'Tom'
      9. }
  • 相关阅读:
    新版Chromedriver在哪下载(Chromedriver 116.0.5845.188的寻找之旅)
    AKHQ Nomad 部署方案
    没有PDF密码,如何解密文件?
    一篇文章教你Pytest快速入门和基础讲解,一定要看
    汽车搭载的车载摄像头分类
    MACday1
    C# winform 窗体缩放问题处理
    MATLAB数据导入
    贪心算法专题小结——区间相关问题
    Raven2靶机渗透
  • 原文地址:https://blog.csdn.net/weixin_51642358/article/details/126414438