• 学习react(二)组件


    1、函数式组件

        function Demo(){
          return <h1>Hello World</h1>;
        }
        ReactDOM.render(<Demo/>, document.getElementById('app'));

      执行了 ReactDOM.render(<Demo/>, document.getElementById('app'));后,react帮我们进行的操作:

        「1」React解析组件标签,找到了Demo组件;

        「2」发现组件是使用函数定义的,然后调用该函数,将返回的虚拟dom转换为真实dom,然后添加到dom树上,最后呈现到页面中。

     2、类式组件

      ES6类:

        「1」类中的构造器不是必须写的,要对实例进行一些初始化操作,例如添加指定属性时才写;

        「2」如果A类继承了B类,且A类中写了构造器,那么A类构造器中的super是必须要调用的;

        「3」类中所定义的方法,都是放在了类的原型对象上,供实例去使用。

    //类式组件
      class Demo extends React.Component {
        render () {
          return <h1>Hello World</h1>;
        }
      }
    
      ReactDOM.render(<Demo/>, document.getElementById('app'))

      执行了 ReactDOM.render(<Demo/>, document.getElementById('app'));后,react帮我们进行的操作:

        「1」React解析组件标签,找到了Demo组件;

        「2」发现组件是使用类定义的,然后new出来该类的实例,并通过该实例调用原型上的render方法;

        「3」将render返回的虚拟dom转换为真实dom,然后添加到dom树上,最后呈现到页面中。

    3、组件三大属性之一state 

      在类组件内使用state

    class Demo extends React.Component {
         constructor (props) {
          super(props)
            this.state = {
                msg: 'hello world'
            }
        }
        render () {
          const {msg} = this.state
          return <h1>{msg}</h1>;
        }
      }
    
      ReactDOM.render(<Demo/>, document.getElementById('app'))

      在类组件内使用函数

    class Demo extends React.Component {
        constructor (props) {
          super(props)
          //因为内部的函数调用是通过类的调用,而不是通过类的实例对象的调用,所以函数内部的this指向为undefined,需要借助bind来修改类内部的this指向
          this.click = this.click.bind(this)
          this.state = {
            hot: true,
          }
        }
    
        render () {
          console.log(this)
          const { hot } = this.state
          //这里注意不能写this.click(),因为传递给onClick的应该是一个函数,如果写this.click()那么就调用了click这个函数,把这个函数的返回值赋给了onClick
          return <h1 onClick={this.click}>今天天气很{hot ? '热' : '冷'}</h1>;
        }
    
        click () {
          //react内实现变量的响应式需要使用this.setState()
          this.setState({
            hot: !this.state.hot,
          })
        }
      }
  • 相关阅读:
    Effective C++ 学习笔记(12)
    Effective C++ 学习笔记(6)
    Effective C++ 学习笔记(13)
    Effective C++ 学习笔记(11)
    Effective C++ 学习笔记(10)
    (转)C++函数后加const的意义
    Effective C++ 学习笔记(14)
    Effective C++ 学习笔记(7)
    Effective C++ 学习笔记(9)
    Effective C++ 学习笔记(8)
  • 原文地址:https://www.cnblogs.com/cuteyuchen/p/16403144.html
Copyright © 2020-2023  润新知