홈>
<li>
를 생성하는 jsx 파일이 있습니다
페이지로드시 요소 이
<li>
항목은 ajax 반환 값을 기반으로 생성됩니다.
각
<li>
마다
요소 프로그래밍 방식으로 "click"이벤트를 추가하고 있으며, 반응 함수 (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
-
답변 # 1
관련 자료
- reactjs - React가 함수 오류가 아닌 원인은 무엇입니까?
- node.js - 반응 네이티브 프로젝트 설치 오류
- javascript - React 코드에서 ESLint no-return-assign 및 no-param-reassign 오류
- javascript - jquery는 하나의 클래스에만 더 많은 함수 대상 p 태그를 표시합니다
- css - typeerror - styled_components__webpack_imported_module_0 __ defaultvedio는 반응의 함수가 아닙니다
- reactjs - react - 주요 app () 함수에 값을 어떻게 전달할 수 있습니까?
- Azure Function Proxy - azure 함수 프록시 - 콜드 스타트 업 :오류 429 너무 많은 요청
- javascript - 모달에서 함수를 전달할 때 React Native "onPress는 함수가 아닙니다"
- javascript - Map 함수는 React JSX에서 항목을 반환하지 않습니다
- javascript - React 함수 구성 요소로 현재 객체에 대한 핸들을 얻는 방법
- reactjs - 후크 useState에 반응하도록 함수를 설정하는 더 좋은 방법이 있습니까?
- javascript - react 및 nodejs를 시작하려고 할 때 NPM 오류
- javascript - react 및 redux - 401 unauthorized error post api 요청
- javascript - 반응에서 표현으로의 오류 404 POST 양식 데이터
- javascript - React stateless 컴포넌트 내부에 함수를 정의해도 괜찮습니까?
- c - 함수 'main'에서 - 오류 : 이진 %에 대한 유효하지 않은 피연산자 ( 'float'및 'int'포함)
- javascript - 마지막 함수를 실행하는 React useEffect
- php - 오류 - 테스트를 실행할 때 null에서 멤버 함수 store () 호출
- reactjs - typeerror - patientmap은 함수가 아닙니다 react js
- javascript - dict 데이터를 jquery에 전달하지 못했습니다 오류 표시 - uncaught syntaxerror : missing) after argument list)
솔루션 1 :해당 메소드 내의 모든 기능을 팻 화살표로 변환하면 모든 것이 작동합니다.
예 :
다음으로 변경 :
솔루션 2 :this 키워드의 참조를 변수에 저장하고 대신 해당 변수에 액세스하십시오.
예 :