2016-03-30 7 views
5

In neuen ES6 Klassen Reagieren this wie hier angegeben binded werden muss: http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding für zB:Warum Bindung in ES6 benötigt wird, reagieren Klassen

class Counter extends React.Component { 
    constructor() { 
    super(); 
    this.tick = this.tick.bind(this); 
    } 
    tick() { 
    ... 
    } 
    ... 
} 

Die Erklärung dafür ist, dass es das Standardverhalten ist jedoch, wenn ich mache eine ES6 Klasse und dann mache ich eine neue Instanz davon this wird

import React from 'React' 

class Test extends React.Component { 
    constructor() { 
     super() 
    } 
    foo() { 
     console.log('bar') 
    } 
    hello() { 
     this.foo() 
    } 
} 

var test = new Test() 
test.hello() 
// > bar 

binded werden Warum Bindung benötigt wird, in Reaktion dann?

Antwort

5

Sie müssen this Verfahren im Fall eingestellt, zum Beispiel, wenn Sie Funktion Bezug auf Event-Handler übergeben müssen, aber nicht wahr this für jede Methode einstellen muß.,

class Counter extends React.Component { 
    constructor() { 
    super(); 
    this.tick = this.tick.bind(this); 
    } 

    tick() { 
    // this refers to Counter 
    } 

    fn() { 
    // this refers to Counter 
    } 

    withoutBind() { 
    // this will be undefined or window it depends if you use "strict mode" or not 
    } 

    render() { 

    this.fn(); // this inside this method refers to Counter 

    // but if you will do like this 
    const fn = this.fn; 
    fn(); // this will refer to global scope 


    return <div> 
     <button onClick={this.tick}>1</button> 
     <button onClick={this.withoutBind}>2</button> 
    </div>; 
    } 
} 

Example