zoukankan      html  css  js  c++  java
  • ES6中bind(this)用法说明

    在使用 React 中的 Class extends写法,如果 onClick 绑定一个方法就需要 bind(this),如果使用React.createClass 方法就不需要

    解析:

    React.createClass 是ES5 的写法默认绑定了 bind 写法
    在 ES6 中新增了class,绑定的方法需要绑定 this,如果是箭头函数就不需要绑定 this

    示例:

    第一种写法:

    _handleClick(e){
      console.log(this);
    }
    render(){
      return (
         <div><h1 onClick={this._handleClick.bind(this)}>点击<h1></div>
     )
    }

    第二种写法:

    constructor(props){
           super(props);
           this._handleClick=this._handleClick.bind(this)
      }
     _handleClick(e){e}{
         console.log(this);
    }
    render(){
       return(
          <div><h1 onClick={this._handleClick}>点击</h1></div>
      )
    }

    第三种写法:

      _handleClick=(e)=>{
            //使用箭头函数
           console.log(this);
     }
    render(){
       return (
          <div><h1 onClick={this._handleClick}>点击</h1></div>
      )
    }
  • 相关阅读:
    [Linux]
    [.Net]
    [.Net]
    [Linux]
    [Google]
    面向对象的7个基本设计原则
    windows SDK中的wininet写http客户端
    C++ 用libcurl库进行http通讯网络编程
    感悟
    关于Windows高DPI的一些简单总结
  • 原文地址:https://www.cnblogs.com/YooHoeh/p/9300942.html
Copyright © 2011-2022 走看看