render라는 함수의 기능이 props나 state의 값이 바뀌면 render함수가 호출되도록 약속되어 있다.
debugger 라고 되있는 부분에서 실행을 멈추고 sources에서 여러가지 정보를 얻을 수 있음.
이벤트가 발생한 태그의 기본적인 동작방법을 못하게 막는 것. 즉, 페이지가 전환되지 않음.
var obj = {name:'egoing'}
> undefined
function bindTest(){
console.log(this.name);
}
> undefined
bindTest();
>undefined
// 당연히 undefined가 나온다. bindTest의 this는 어떤 걸 가리키는 지 모르기 때문
var bindTest2 = bindTest.bind(obj);
>undefined
bindTest2(this.name);
>egoing
...
return (
...
<header>
<h1><a href="/" onClick={function(e){
console.log(e);
e.preventDefault();
this.state.mode = 'welcome';
}.bind(this)}>{this.state.subject.title}</a></h1>
)
위와 같이 직접적으로 state를 변경하는 문장을 삽입하면 this.state.mode가 'welcome'으로 바뀌지 않는다. 컴포넌트가 생성된 다음에 동적으로 state값을 바꾸려면 절대 위와 같이 직접 바꾸면 안되고 함수의 값으로 바꿔야 한다.
return (
...
<header>
<h1><a href="/" onClick={function(e){
console.log(e);
e.preventDefault();
this.setState({
mode: 'welcome'
});
}.bind(this)}>{this.state.subject.title}</a></h1>
)
그럴땐 위와 같이 setState를 사용하면 바뀐다.
constructor부분에서는 아래와 같이 쓰면 된다.
class App extends Component {
constructor(props) {
super(props);
this.state = {
mode: 'read',
subject:{title:'WEB', sub:'World Wide Web'};
content:[
{id:1, title:'HTML', desc:'HTML is for information'}
]
}
}
}
return (
...
<header>
<h1><a href="/" onClick={function(e){
console.log(e);
e.preventDefault();
this.setState({
mode: 'welcome'
});
}.bind(this)}>{this.state.subject.title}</a></h1>
</header>
)
this.setState에 객체형태로 값을 줘야 한다. 리액트 입장에서는 위와 같이 state값을 바꾸게 되면 리액트 입장에서는 몰래 바꾼 셈이다. 값이 바뀌었는지 모르니까 랜더링할 수 없다. 그래서 setState로 바꾸어야 한다.
이벤트를 만드는 생산자가 되보자!
App컴포넌트 내의 Subject라는 컴포넌트에 onChangePage라는 이름의 이벤트를 만들어보자.
return (
<div className="App">
<Subject
title={this.state.subject.title}
sub={this.state.subject.sub}
onChangePage={function(){
alert('hihihi')
}.bind(this)}
>
</Subject>
)
Subject컴포넌트에 a태그 안에 onClick이벤트를 사용하여 클릭하면 onChangePage가 실행되도록 작성한다.
...
<h1><a href="/" onClick={function(e){
e.preventDefault();
this.props.onChangePage();
}.bind(this)}>{this.props.title}</a></h1>
onChangePage이벤트가 발생되었을 때 props로 전달된 onChangePage라는 함수를 호출하면 된다. 이 상태에서 this.setState({mode:'welcome'})으로 바꾼다.
그러면 onChangePage함수가 실행되었을 때 mode가 welcome으로 바뀐다.
그럼 그에 따라 화면도 변경되는 걸 확인할 수 있다.
return (
<div className="App">
<Subject
title={this.state.subject.title}
sub={this.state.subject.sub}
onChangePage={function(){
this.setState({mode:'welcome'})
}.bind(this)}
>
</Subject>
)