2016-03-30 16 views
5

a New Reagire classi ES6 this ha bisogno di essere rilegata come indicato qui: http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding per esempio:Perché vincolante è necessario in ES6 reagiscono classi

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

La spiegazione di questo è perché è il comportamento di default, se faccio una classe ES6 e poi faccio una nuova istanza di esso this verrà rilegato

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 

Perché è necessario obbligatorio in Reagire, allora?

risposta

5

È necessario impostare this ai metodi nel caso in cui, ad esempio, se avete bisogno di passare funzione di riferimento per i gestori di eventi, tuttavia non è necessario impostare this per ogni metodo.,

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

Problemi correlati