我有一个jsx文件,它在页面加载时创建<li>
元素。这些<li>
项是基于ajax返回值创建的。
对于每个<li>
元素,我都会用程序添加"点击"事件,它会调用一个反应函数(friendChat(。但是在实现这个过程中,我得到了以下错误。(但我可以获得其他属性。这些属性在构造函数中初始化。(
- 错误:this.friendCap不是函数
下面是我的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
解决方案1:将该方法中的所有函数转换为胖箭头,一切都会正常工作。
示例:
$(document).ready(function(){...})
更改为:
$(document).ready(()=>{...})
解决方案2:将此关键字的引用存储到一个变量中,然后访问该变量。
示例:
componentDidMount() {
const self = this;
....
self.friendChat(self.id);
}