javascript - React.js: onClick function from child to parent -
i used this article example (react way), not working me. please point me mistake, can't understand what's wrong.
this error see:
uncaught typeerror: this.props.onclick not function
here code:
// parent var senddocmodal = react.createclass({ getinitialstate: function() { return {taglist: []}; }, render: function() { return ( <div> { this.state.taglist.map(function(item) { return ( <tagitem nameprop={item.name} idprop={item.id} onclick={this.handleremove}/> ) }) } </div> ) }, handleremove: function(c) { console.log('on remove = ', c); } }); // child var tagitem = react.createclass({ render: function() { return ( <span classname="react-tagsinput-tag"> <span>{this.props.nameprop}</span> <a classname='react-tagsinput-remove' onclick={this.handleremove}></a> </span> ) }, handleremove: function() { this.props.onclick(this); } });
thanks in advance!
the issue this
inside map
callback not refer react component, hence this.handleremove
undefined
.
you can set this
value explicitly passing second argument map
:
this.state.taglist.map(function() {...}, this);
now this
inside callback refers same value this
outside callback, namely senddocmodal
instance.
this has nothing react, it's how javascript works. see how access correct `this` context inside callback? more info , other solutions.
Comments
Post a Comment