reactjsthislisteners

reactjs this context is changed inside on change method how call function


This is change, when I call on, event listener (instead of on onClick method in an element, because I use bootstrap select2).

getReviewVacancyUpdate(post_id) {
    console.log(post_id);
}

componentDidMount() {
   $('#post_list').on('change', function(e) {          
       this.getReviewVacancyUpdate(this.value); //function in undefined
   });
}

Is it anyway to save previous this state? Maybe bind it? And call the component method. Without error - "function is undefined"

I can add class to the beginning of jsx.

var Child = React.createClass({
statics: {
    getReviewVacancyUpdate: function(post_id) { 
        console.log(post_id);
        return true;
    }
},
// ...
render() {

}
});

But it doesn't look good


Solution

  • So i add let variable to save this context before on change method invokes. And everything works fine.

    componentDidMount() {
         let save_this = this;
         $('#post_list').on('change', function(e){
               let selected = $(e.currentTarget).find("option:selected").val();
               save_this.getReviewVacancyUpdate(selected);
         }).bind(this);
    }