javascript - Default functions in React.js -


i have snippet that, works:

class button extends react.component {     state = { counter : 0 }   handleclick = () => {     this.setstate({         counter: this.state.counter+1     })   }    render() {     return (         <button onclick={this.handleclick}>           {this.state.counter}         </button>     )   } } 

above, handleclick function arrow one. below, instead i'm trying use default function (from es5):

 class button extends react.component {     state = { counter : 0 }   handleclick = function() {     this.setstate({         counter: this.state.counter+1     })   }    render() {     return (         <button onclick={this.handleclick}>           {this.state.counter}         </button>     )   } }  reactdom.render(<button/>, mountnode) 

the problem second snippet don't work in function's writing way? or somewhere else? react js not handle default functions?

when write this:

class example {   handleclick = (e) => {     this.dostuff(e);   } } 

it's being transpiled babel this:

var example = function example() {   var _this = this;    this.handleclick = function (e) {     return _this.dostuff(e);   }; }; 

the method handleclick has access object's instance because constructor stores instance in variable _this , method forms closure _this available in lexical environment. uses _this instead of keyword this, because when called event listener doesn't know original object, this have value window (or undefined if strict mode enabled).



now, when use regular function instead of arrow function, so:

class test {   handle = function (e) {      return this.dostuff(e);   } } 

it's transpiled instead:

var test = function test() {   this.handle = function (e) {     return this.dostuff(e);   }; }; 

as can see, it's trying access instance via keyword this, won't object instance when method called event listener, won't work expected.



if you're dreamer me , thinking world "class properties transform" part of actual spec , we're using es2xxx natively, can think of arrow function version equivalent following:

class example {   constructor() {     this.handleclick = (e) => {       this.dostuff(e);     }   } } 

you can see here it's creating arrow function in constructor, , since arrow functions take context (i.e. value of this) surrounding scope, , scope here constructor itself, this have appropriate value, no matter method called.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -