javascript - React onClick event yields: "Uncaught TypeError: Cannot read property of undefined", despite binding -
i'm writing react script render bunch of <a />
elements defined array.
... render: ... var behaviourcomponents = this.props.myobjectarray.map(function(element) { return <a classname="crumbfile" onclick={this._myfunction.bind(this,element.value1)}>{element.value2}</a>; }); return ( ... <div>{behaviourcomponents}</div> ...)
this works fine when there no function call onclick. however, when there error: "uncaught typeerror: cannot read property '_myfunction' of undefined".
this strange because have component right before onclick function call works fine (<a class="btn header" style={buttonstyle} onclick={this._onload}>load</a>
), makes me think scoping issue due map() function. however, used .bind(), not sure what's wrong here.
this because context inside of function pass map()
not referring react component class. default, context global window object.
there few ways solve issue:
1) bind correct context of this
function passed map()
.
this.props.myobjectarray.map(function(element) { ... }.bind(this));
2) pass correct context second argument map()
this.props.myobjectarray.map(function(element) { ... }, this);
3) use es6 arrow function, bind correct context you.
this.props.myobjectarray.map(element => { ... });
Comments
Post a Comment