我有一个jsx文件,它在页面加载时创建<li>
个元素。这些<li>
项是根据ajax返回值创建的。
对于每个<li>
元素,我以编程方式添加“click”事件,该事件调用react函数(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
答案 0 :(得分:1)
解决方案1:将该方法中的所有函数转换为fat-arrow,一切都会正常工作。
示例:
SetTitleMatchMode,2 ;;; allows for a partial search
#IfWinActive, .py ;;; scope limiter to only python files
:b*:print ::print(){Left} ;;; I forget what b* does
#IfWinActive ;;; remove the scope limitation
转变为:
$(document).ready(function(){...})
解决方案2:将this关键字的引用存储到变量中,然后访问该变量。
示例:
$(document).ready(()=>{...})