zoukankan      html  css  js  c++  java
  • react事件this指向 this丢失

    react在事件监听时可能会导致this指向丢失,以下几种方式可以修正这个问题

    1.嵌套箭头函数

      

     <button onClick={(e)=>this.fn1(e)}>按钮fn1</button>

      箭头函数可以修正fn1函数内部的this指向,但如使用事件对象的话需要显式传递事件对象参数

    2.监听的函数是箭头函数

    <button onClick={this.fn2}>按钮fn2</button>
    
    
    
    //fn2
    
     fn2=(e)=>{
            console.log("fn2 箭头函数")
            console.log(this)
            console.log(e.target)
        }

    3.监听时使用bind

     <button onClick={this.cl.bind(this)}>按钮cl</button>

    4.构造函数预先绑定bind

       <button onClick={this.fn}>按钮fn</button>
    
    
    //
    
    class APP extends React.Component{
        constructor() {
            super();
            this.fn=this.fn.bind(this)
        }
    
     fn(e){
            console.log("方法")
            console.log(this)
            console.log(e.target)
        }
      render() {
            return (
      <button onClick={this.fn}>按钮fn</button>
          )
    }

    构造函数绑定权重较高,如果构造函数绑定之后,在jsx中再次使用bind方法绑定别的对象,仍会是构造函数绑定的this

  • 相关阅读:
    smarty语法
    combobox里面显示checkbox
    requirejs打包项目
    datagrid中用tooltip
    combobox默认值为第一个数据,修改为空值
    easyui-textbox高为0
    C++并发编程 异步任务
    C++并发编程 互斥和同步
    C++并发编程 thread
    C++智能指针
  • 原文地址:https://www.cnblogs.com/anin/p/13529486.html
Copyright © 2011-2022 走看看