티스토리 뷰

 

Vanilla JS로 컴포넌트 방식을 사용하여 웹페이지를 만들던 중 

appendChild를 통해 부모 컴포넌트에 자식 컴포넌트를 append 하는 과정에서 아래와 같은 에러가 발생했다.

해당 글에서 칭하는 컴포넌트는 javascript class를 말한다.

Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')

 

자식 컴포넌트 생성시에 인자를 넘겨주어야 하는 상황이었는데 

해당 에러때문에 부모 컴포넌트에 자식 컴포넌트가 append 되지 않았다.

 

원인은 부모 컴포넌트에서 자식 컴포넌트를 생성시 인자를 넘겨줄 때 중괄호를 누락시켰기 때문에 발생했고 

아래 코드에 적은 대로 $target이 아닌 ${target}으로 넘겨 주어야 했다.

export default class App {
    constructor($target){        
        const searchSection = new SearchSection($target); 
        // $target(x), ${target}(o)
    }
}

 

짚고 넘어갈 것은 $target으로 넘겨주면 안되는 것이 아니라 

자식컴포넌트에서 받는 방법에 따라 넘겨주는 방법이 달라진다는 것이다.

 

부모 컴포넌트에서 ${target}으로 넘겨주면 자식 컴포넌트에서도 ${target}으로 받아야 하며

부모 컴포넌트에서 $target으로 넘겨주면 자식 컴포넌트에서도 $target으로 받아주어야 한다.

// 부모 컴포넌트
export default class App {
    constructor($target){
    	// 자식 컴포넌트 생성
        const searchSection = new SearchSection({$target}); // {$target}으로 넘겨줌
    }
}

// 자식 컴포넌트
export default class SearchSection {
	// 자식 컴포넌트 생성자
    constructor({$target}) {  // {$target}으로 받음
        this.section = document.createElement("section");
        $target.appendChild(this.section);
        this.render();
    }
    
    render() {
      const wrapper = document.createElement("div");
      this.section.appendChild(wrapper);
    }
}

 

결론은 일관성있게 적으면 된다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함