我正在使用Javascript和React来构建前端。我不知道如何引用包含对象的方法:
$scope.myFunc = function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
我正在 var RAttribute = React.createClass({
loadAssignmentsForList: function(elem) {
//other code
},
render: function() {
var assignmentsLoading = this.props.assignmentsLoading;
var lists = this.props.data.lists.map(function(elem) {
return (<li className='list-group-item grey'>
<div className='list-group'>
<RList key = {elem.name} data={elem}
assignmentsLoading={assignmentsLoading}
loadAssignmentsForList={this.loadAssignmentsForList(elem)}/>
</div>
</li>);
});
//other code
}
//other code
});
内拨打loadAssignmentsForList
,因此我正在使用render
。但是,我收到以下错误。
this.loadAssignmentsForList(elem)
答案 0 :(得分:2)
将.this
绑定到.map
,this
中的.map
未引用RAttribute
对象
var lists = this.props.data.lists.map(function(elem) {
// your code
}.bind(this));
或者您可以通过第二个参数将this
设置为.map
,如此
var lists = this.props.data.lists.map(function(elem) {
// your code
}, this);
另外,如果您使用的是ES6
,则可以使用arrow functions
var lists = this.props.data.lists.map((elem) => {
// your code
});