kapuchaster kapuchaster - 1 year ago 93
React JSX Question

ReactJS call class method in Button after map()

I have 2 JS classes: App.jsx, Note.jsx.


export default class Note{
constructor(text) {
this.text = text;


In App.jsx:

let tmpNote = new Note(String(this.state.value));
this.notes.push({key:this.currId, value:tmpNote});

and in App.jsx i can call the changeNoteStatus() on a simple object but after creating a list of Note and using map() function:

return this.notes.map((obj) =>
<div className="note" onClick={obj.value.changeNoteStatus} key={obj.key} id={"note_" + obj.key}/>

The method doesn't recognize class field anymore (like this.text).

I have tried
in mapping function too.

Please help me.

Answer Source

When you use it in an onClick like that, the handler will get called with the wrong this value.

One solution is to use Function#bind:

// --------------------------------^^^^^^^^^^^^^^^^

...but depending on how your overall code is structured, there may be more concise or efficient ways of doing it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download