📌 참고 📌
https://www.youtube.com/watch?v=h7GdhY_m8nM&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=21
링크를 클릭했을 때 실행되는 이벤트
onClick
은 리액트 문법으로, html tag
에서는 onclick
으로 사용된다.
onClick={}
중괄호로 묶어서 적당한 코드를 작성한다.
<a href="/" onClick={function(e){
// 이벤트가 실행될 때 기본적으로 동작되는
// 페이지 전환(reload) 현상을 막는다.
e.preventDefault();}}>
</a>
함수 안에서는 this
값을 인식하지 못하므로 bind
해주어야 한다.
함수 밖의 this
를 함수 안에 주입하면 함수 밖 this
값이 연결되어
함수 안에서도 this
를 사용할 수 있다.
onClick={function(e){
console.log(e);
e.preventDefault();
}.bind(this)} // 함수가 끝난 직후에 사용
render()
메서드 밖에서 ES6 의 화살표 함수로
이벤트 함수를 만들어 호출하면 bind
없이 this
를 사용할 수 있다.
onClick = (e) => {
console.log(e);
e.preventDefault();
this.setState({
mode: 'init'
});
}
render() {
...
return(
<h1>
<a href="/" onClick={this.handleClick}>
{this.state.subject.title}
</a>
</h1>
{this.state.subject.sub}
);
}
constructor
안에서 미리 bind
된 값을 넣어주면
해당 함수의 정의하는 부분 끝에 bind
를 일일히 작성하지 않아도 된다.
constructor(props){
this.inputFormHandler = this.inputFormHandler.bind(this);
}
상위 컴포넌트의 이벤트 함수를 호출하는 방법
/* 상위 컴포넌트 [App.js] */
onChangePage={function(){
this.setState({mode:'init'});
}.bind(this)}>
/* 하위 컴포넌트 [Subject.js] */
<a href="/" onClick={function(e){
e.preventDefault();
// 상위 컴포넌트 onChangePage 함수를 호출
this.props.onChangePage();
}.bind(this)}>{this.props.title}</a>
data-
접두사 속성은 e.target.dataset
로 접근한다.
/* 상위 컴포넌트 [App.js] */
onChangePage={function(id){
this.setState({
mode: 'read',
// string
selectedId: Number(id)
});
}.bind(this)} data={this.state.contents}>
/* 하위 컴포넌트 [Toc.js] */
<a href={"/content/"+data[i].id}
data-id={data[i].id}
onClick={function(e){
e.preventDefault();
// data-id(접두사) 속성은 dataset 로 접근
this.props.onChangePage(e.target.dataset.id);
}.bind(this)}>{data[i].title}</a>
/* 상위 컴포넌트 [App.js] */
onChangePage={function(id){
this.setState({
mode: 'read',
// string
selectedId: Number(id)
});
}.bind(this)} data={this.state.contents}>
/* 하위 컴포넌트 [Toc.js] */
<a href={"/content/"+data[i].id}
data-id={data[i].id}
// 첫 번째 매개변수 값으로 id = id(data[i].id) 값을 넣는다.
onClick={function(id,e){
e.preventDefault();
this.props.onChangePage(id); // function(id)
// bind 매개변수 값에 data[i].id 을 추가
}.bind(this, data[i].id)}>{data[i].title}</a>