gpt4 book ai didi

javascript - ReactJS中未定义的函数

转载 作者:行者123 更新时间:2023-12-02 17:20:37 25 4
gpt4 key购买 nike

不确定我在这里做错了什么,但基础知识是:

/** @jsx React.DOM */

/**
* Deal with creating a set of posts for a table.
*/
var PostRow = React.createClass({

handleDelete: function(id){
var postToDelete = AisisWriter.Models.Post();
postToDelete.set({id: this});
posttoDelete.destroy().then(this.deleted, this.fail)
return false;
},

deleted: function() {
console.log('Success - check the db for this post');
},

fail: function() {
console.log('Fail');
},

render: function(){
// Loop through the post objects.
var post = this.props.posts.map(function(postObject) {
var content = null;
var title = null;

// Cut off the text at anything over 140 characters
if (postObject.content.length > 140){
content = postObject.content.substr(0, 140) + '...';
}else{
content = postObject.content;
}

// Cut off the text at anything voer 20 characters
if (postObject.title.length > 20){
title = postObject.title.substr(0, 20) + '...';
}else{
title = postObject.title;
}

// Return the rows of the table.
// React makes us have a unique key.
return (
<tr key={postObject.id}>
<td>{title}</td>
<td>{content}</td>
<td>
<a href={"#/post/" + postObject.id} className="btn btn-primary move-right-10px">View</a>
<a href={"#/post/" + postObject.id + '/edit'} className="btn btn-success move-right-10px">Edit</a>
<button className="btn btn-danger" onClick={this.handleDelete(postObject.id)}>Delete</button>
</td>
</tr>
);
});

// Finially return the rows (note the div)
return (
<div>{post}</div>
);
}
});

我遇到的问题是,如果我这样做: this.handleDelete life is grand,页面就会加载。但我需要传入这个特定帖子 id 的 id,所以我尝试执行您所看到的操作: this.handleDelete(postObject.id) 那时我得到: Uncaught TypeError : 总体来说,undefined 不是一个函数this.handleDelete(postOject.id)

我是不是已经进入回电 hell 了?我做错了什么吗?

最佳答案

当使用Array.prototype.map时,函数的上下文默认属于全局范围,即 this 引用浏览器中的 window。当您调用 map 时,您可以将上下文传递给它以将其设置为组件,就像您的代码所期望的那样:

// Add a `this` as the second argument to `map` to set the context to
// the current component. `this.handleDelete` will then refer to the component's
// `handleDelete` function like you are expecting.
var post = this.props.posts.map(function(postObject) {
...
<button className="btn btn-danger" onClick={this.handleDelete.bind(this, postObject.id)}>Delete</button>
...
}, this);

您还需要bind传递 postObject.id 的回调函数。

// The current form is a function call
this.handleDelete(postObject.id)

// `bind` returns a new function that will be passed `postObject.id` when it is
// called by React.
this.handleDelete.bind(this, postObject.id)

关于javascript - ReactJS中未定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23999054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com