kapuchaster kapuchaster - 10 days ago 8
React JSX Question

ReactJS call class method in Button after map()

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

Note.jsx:

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

changeNoteStatus(){
console.log(this.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
{this.notes[obj.key].changeNoteStatu}
in mapping function too.

Please help me.

Answer

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:

onClick={obj.value.changeNoteStatus.bind(obj.value)}
// --------------------------------^^^^^^^^^^^^^^^^

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