javascript - React event-handling (onClick) inconsistency -
sup.
the following alerts on render, not onclick:
render: function(){ return ( <div onclick={alert('i alert on render, not onclick.')} /> ); }
same following:
foo : function(text) { alert(text) }, render: function(){ return ( <div onclick={this.foo('i alert on render, not onclick.')} /> ); }
this nothing:
foo : function(text) { alert(text) }, render: function(){ return ( <div onclick={function(){this.foo('what click , must it, huh?')}} /> ); }
although works expected:
render: function(){ return ( <div onclick={function(){alert('i alert onclick only.')}} /> ); }
note each code block exists inside react class , omitted styling creates area that's clickable. note alerts in first 2 cases pop twice each, believe because web app uses react-router.
i have 2 questions:
- for first 2 cases, why need anonymous function prevent alert on render?
- why
foo()
not called onclick in 3rd case, alert triggered in last case?
for q1 suspect understanding of eventhandlers bit off , q2, well, i'm dumbfounded.
thanks in advance.
- for first 2 cases, why need anonymous function prevent alert on render?
what have between curly braces evaluated , hence showing alert message on render.
- why foo() not called onclick in 3rd case, alert triggered in last case?
it called this
not context expect because creating anonymous function. inside function context doesn't have foo
method. need way attach proper context, example, using function.prototype.bind:
foo : function(text) { alert(text) }, render: function(){ return ( <div onclick={this.foo.bind(this, 'what click , must it, huh?')}>click</div> ); }
see demo.
Comments
Post a Comment