zoukankan      html  css  js  c++  java
  • React 之 面向组件编程

    什么是组件?

    用来实现局部功能效果的代码和资源的集合(html/css/image等等)

    为什么要使用组件?

    作用:复用编码,简化项目编程,提高运行效率

    官方提供了两种定义组件的方式

    1.函数式组件

    特点:适用于[简单组件]的定义

    一.函数式组件

    // 创建函数式组件
        function MyComponent(){
          console.log(this) // 此处的this是undefined 因为babel编译后开启了严格模式
          return <h2>我是函数定义的组件</h2>
        }
        ReactDOM.render(<MyComponent/>,document.getElementById('test'))
        /* 
           执行了ReactDOM.render后发生了什么?
           1.React解析组件标签,找到了MyComponent组件
           2.发现组件是使用函数定义的,随后调用该函数,将返回的虚拟dom转为真实的dom,随后呈现在页面中
    
        */

    二.类式组件

     class MyComponent extends React.Component {
          render(){
            /* 
               render是放在哪里的? --MyComponent的原型对象上,供实例使用 
               render中的this是谁? --MyComponent的实例对象,也可以说MyComponent组件实例对象 = 组件对象
            */
            console.log('render中的this:',this)
            return <h2>我是用类定义的组件(适用于[复杂组件]的定义)</h2>
          }
        }
        // 2.渲染到页面
        ReactDOM.render(<MyComponent/>,document.getElementById('test'))
        /* 
           执行了ReactDOM.render(<MyComponent/>.....)后发生了什么?
           1.React解析组件标签,找到MyComponent组件
           2.发现组件是使用类定义的,随后new出来类的实例,并通过实例去调用render方法
        */

    类的复习

    class Person {
            // 构造器方法
            constructor(name,age){
              //构造器中的this是谁? 类的实例对象
              this.name= name
              this.age = age
            }
            // speak方法放在了哪里? Person类的原型对象上,供实例使用
            speak(){
              console.log(`我叫${this.name}, 我的年龄是${this.age}`);
            }
          }
          const p1 = new Person('tom',18)
          p1.speak()
          console.log(p1);
        
        
          class Student extends Person {
            constructor(name,age,grande){
              super(name,age) //必须在第一行
              this.grande = grande
            }
            //重写从父类继承过来的方法
            speak(){
              console.log(`我叫${this.name}, 我的年龄是${this.age},我的年级是${this.grande}`);
            }
          }
    
          const s1 =  new Student('小行',30,'一年级')
          s1.speak()
          console.log(s1)

    总结:
    1.类中的构造器不是必须要写的,要对实例进行一些初始的从操作,如添加指定属性时才写
    2.如果A类继承了B类,且A类中写了构造器,那么A类构造器中的super是必须要调用的
    3.类中所定义的方法,都是放在了类的原型对象上,供实例去使用
  • 相关阅读:
    【插件开发】—— 10 JFace开发详解
    百度地图POI数据爬取,突破百度地图API爬取数目“400条“的限制11。
    Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)
    Python 3.X 要使用urllib.request 来抓取网络资源。转
    python创建目录保存文件
    Python返回数组(List)长度的方法
    python中for、while循环、if嵌套的使用
    (转)python3 urllib.request.urlopen() 错误UnicodeEncodeError: 'ascii' codec can't encode characters
    python 之 string() 模块
    (转)Python3异常-AttributeError: module 'sys' has no attribute 'setdefaultencoding
  • 原文地址:https://www.cnblogs.com/zmztya/p/14623661.html
Copyright © 2011-2022 走看看