Trying To Pass OnChange Function As Props To GrandChlidren Result Into TypeError: This Is Undefined
I am trying to pass a onChange function the parent to grandChild but getting error TypeError: this is undefined The code is as follow var Tablefortask = React.createClass({
Solution 1:
That's happening because this is not refering to your component inside your map function.
To fix it, you have to bind the context passing it as the second argument to the map function.
var commentNodes = this.props.data.map(function(comment) {
return (
<Addcontenttotable onChange= {this.props.onChange} taskName={comment.taskName} standarDescription={comment.standarDescription} emplComment={comment.emp_comment} empRating={comment.empRating} key={comment.id} reviewComment={comment.review_comment} reviewRating={comment.review_rating} >
</Addcontenttotable>
);
},this);
If you are using ES6 you can use fat arrow functions to preserve the context.
var commentNodes = this.props.data.map((comment) => {
return (
<Addcontenttotable onChange= {this.props.onChange} taskName={comment.taskName} standarDescription={comment.standarDescription} emplComment={comment.emp_comment} empRating={comment.empRating} key={comment.id} reviewComment={comment.review_comment} reviewRating={comment.review_rating} >
</Addcontenttotable>
);
});
Solution 2:
Whenever you get a 'this' error, you have the first solution to look at!
Define a constructor function for your class as below:
var variable = React.createClass({
ctor: function(){
this = self;
},
func1: function(){
//your code
this.anything//error
self.anything//solved
},
func2: function(){
//your code
this.anything//error
self.anything//solved
},
func3: function(){
//your code
this.anything//error
self.anything//solved
}
});
You can just change all the 'this' into 'self' once you have initiated that ctor function as illustrated above!
Solution 3:
Pass this
to your map function this.props.data.map(function(comment) { }, this);
or define var self = this
and use self.props
inside map function.
var TablefortaskList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return (
<Addcontenttotable onChange= {this.props.onChange} taskName={comment.taskName} standarDescription={comment.standarDescription} emplComment={comment.emp_comment} empRating={comment.empRating} key={comment.id} reviewComment={comment.review_comment} reviewRating={comment.review_rating} >
</Addcontenttotable>
);
}, this);
return (
<tbody>{commentNodes}</tbody>
);
}
});
Post a Comment for "Trying To Pass OnChange Function As Props To GrandChlidren Result Into TypeError: This Is Undefined"