• react中this指向问题


    一.行间定义事件后面使用bind绑定this

    run(){
        alert("第一种方法!")
    }
    
    <button onClick={this.run.bind(this)}>第一种</button>
    
    //这一种方法使用bind来修改this的指向,需要注意的是bind括号内第一个参数是修改this的,后面可以设置其他参数进行传值。
    

    二.在构造函数内部声明this指向

    constructor(props) {
        super(props);
        this.state={
            //定义数据
        }
        this.run = this.run.bind(this);
    }
    	
    run(){
        alert("第二种方法!")
    }
     	 
    <button onClick={this.run}>第二种</button>
    
    //第二种方法和第一种方法原理一样,只是写的位置不同。
    

    三.声明事件时将事件等于一个箭头函数

    run=()=> {
        alert("第三种方法!")
    }
    
    <button onClick={this.run}>第三种</button>
    
    //第三种方法是将定义的run方法再等于一个箭头函数,利用箭头函数没有自己的this指针会继承外层的作用域这个特性,来解决this指向问题
    

    四.行间定义事件使用箭头函数

    run(){
        alert("第四种方法!")
    }
    
    <button onClick={()=>this.run()>第四种</button>
    
  • 相关阅读:
    L208
    L207
    L206
    L205 EE
    L204
    监控glusterfs
    监控elssticSearch健康状态
    防火墙
    创建逻辑卷
    编译安装nginx,并使用systemd管理nginx
  • 原文地址:https://www.cnblogs.com/huihuihero/p/11028285.html
Copyright © 2020-2023  润新知