reactjs - Why the scoping of this keyword is invalid in JSX but works in ES6? (Lexical this vs arrow functions) -
i have react component below. why this not defined when changenametwo called?
see jsbin: http://jsbin.com/nuhedateru/edit?js,output
then why works in typical es6 class? see jsbin: http://jsbin.com/kiyijuqiha/edit?js,output
class helloworldcomponent extends react.component { constructor(props) { super(props); this.state = { name : 'yolo' } } changename = () => { this.setstate({name: 'another yolo'}); } changenametwo() { this.setstate({name: 'another yolo'}); } render() { return ( <div> <h1>hello {this.props.name}</h1> <p>name: {this.state.name}</p> <button onclick={this.changename}>change name</button> <button onclick={this.changenametwo}>change name 2</button> </div> ); } } react.render( <helloworldcomponent name="es2015/es6"/>, document.getelementbyid('react_example') );
one dom event, other directly calling. default context of click event element clicked.
it desirable reference element on event handler fired, such when using generic handler set of similar elements.
when attaching handler function element using addeventlistener(), value of inside handler reference element. same value of currenttarget property of event argument passed handler. (mdn - https://developer.mozilla.org/en-us/docs/web/api/eventtarget/addeventlistener)
your methods have default context of instance, if context not specified (a normal function call opposed .call
or .apply
. animal.speak()
default have correct context.
when function called method of object,
this
set object method called on. (mdn - https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/this)
to summarise, click event sets specific context overrides that. know can solve .call/.bind/.apply or onclick={(e) => this.changename(e)}
. implementation today wouldn't that, imagine have keep compatibilities' sake.
Comments
Post a Comment