【发布时间】:2018-02-06 08:02:39
【问题描述】:
我有一个 jsx 文件,它在页面加载时创建 <li> 元素。这些<li> 项是根据ajax 返回值创建的。
对于每个<li> 元素,我以编程方式添加“点击”事件,该事件调用反应函数 (friendChat)。但是在执行此操作时,我收到以下错误。 (但我能够获得其他属性。在构造函数中初始化。)
- 错误:this.friendChat 不是函数
以下是我的 jsx 文件。
提前致谢。
jsx 文件
import React from 'react'
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {username: "Anu"};
this.friendChat = this.friendChat.bind(this);
}
friendChat(friendId)
{
console.log("Clicked friend id: "+ friendId );
}
componentDidMount() {
console.log('Component DID MOUNT!');
$(document).ready(function(){
$.ajax({
type: "GET",
url: "/friends/myFriends",
success: function(data){
if (data == "No friends")
{
console.log("No friends exist");
document.getElementById('friends').innerHTML = "Please add
friends";
}
else
{
console.log("Friends: "+data);
//Displaying friends in div
for (var i = 0; i < data.length; i++)
{
console.log("Friend: "+ data[i]);
var li=document.createElement("li");
//var br=document.createElement("br");
li.appendChild(document.createTextNode(data[i]));
li.setAttribute("id",data[i]);
console.log(this.state.username);
//It's Printing correctusername (Anu) initialised inside
//the constructor
//Adding on click event for each friend
li.addEventListener("click", function() {
this.friendChat(this.id); }, false);
//Here it's showing the error of this.friendChat is not a
//function
//Appending list item to document
document.getElementById("friends").appendChild(li);
}
}
}.bind(this)
});
}
render() {
return (
<div>
<div className="home_recentfriends">
<ul id="friends"></ul>
</div>
</div>
)
}
}
export default Home
【问题讨论】:
-
如果你使用 jquery,为什么你在 ajax jquery 请求中使用 javascript pure,请遵循使用 jquery 但不要在同一个函数中使用 jquery 和 javascript,这会导致像你这样的错误
-
解释得很好。谢谢@Andrew Li。
-
我从@Giovanni Lobitos 得到了准确的答案
-
@abhilash 如果副本有帮助,请点击问题上方的黄色横幅接受副本。