REACT
[생활코딩] 이벤트에서 state 변경하기 / bind함수 / setState함수
worri-pi
2022. 1. 31. 21:14
생활코딩 https://www.youtube.com/watch?v=h7GdhY_m8nM&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=21
import React,{Component} from 'react';
import TOC from "./components/TOC";
import Content from './components/Content';
import Subject from './components/Subject';
import './App.css';
class App extends Component{
constructor(props){
super(props);
this.state={
mode:'read',
subject:{title:'WEB',sub:'world wide web!!'},
welcome:{title:'Welcome',desc:'Hello, React!!'}
}
}
render(){
return(
<div className="App">
<header>
<h1><a href="/" onClick={function(e){
e.preventDefault();
console.log(this);
}}>{this.state.subject.title}</a></h1>
{this.state.subject.sub}
</header>
<TOC data={this.state.contents}></TOC>
<Content title={_title} desc={_desc}></Content>
</div>
);
}
}
export default App;
여기서 console.log 에 undefined 가 나온다.
bindTest 함수에 bind 함수를 또 호출하고 첫 번째 인자로 obj 를 준다.
bind 함수로 인해 bindTest 함수 block 안에 this가 obj로 동작되는 새로운 함수를 만들 수 있다.
bind 함수는 render 함수 안에서 component 인 자기자신 this를 가리킨다. bind 함수를 사용하여 this를 주입한 후 다시 한번 호출을 해줘야 함수 속 this 를 원하는 객체로 지정한 후 값을 얻을 수 있다.
그리고 component가 state 값 생성이 끝난 후 동적으로 바꿀 때 this.state.mode='welcome' 라고 작성하면, react가 state 값을 바꾼 것을 모르기 때문에 mode 값이 바뀌지 않는다.
react가 알 수 있게 this.setState() 함수 안에서 state 값을 바꿔주면 state 값이 바뀌는 것을 확인할 수 있다.
import React,{Component} from 'react';
import TOC from "./components/TOC";
import Content from './components/Content';
import Subject from './components/Subject';
import './App.css';
class App extends Component{
constructor(props){
super(props);
this.state={
mode:'read',
subject:{title:'WEB',sub:'world wide web!!'},
welcome:{title:'Welcome',desc:'Hello, React!!'},
contents:[
{id:1, title:'HTML', desc:'HTML is HyperText ...'},
{id:2, title:'CSS', desc:'CSS is for design'},
{id:3, title:'JavaScript', desc:'JavaScript is for interactive'}
]
}
}
render(){
console.log('App render');
var _title, _desc = null;
if(this.state.mode === 'welcome'){
_title = this.state.welcome.title;
_desc = this.state.welcome.desc;
}else if(this.state.mode === 'read'){
_title = this.state.contents[0].title;
_desc = this.state.contents[0].desc;
}
console.log('render',this);
return(
<div className="App">
<header>
<h1><a href="/" onClick={function(e){
console.log('event in',this);
console.log(e);
e.preventDefault();
this.setState({
mode:'welcome'
})
}.bind(this)}>{this.state.subject.title}</a></h1> //bind 함수 사용
{this.state.subject.sub}
</header>
<TOC data={this.state.contents}></TOC>
<Content title={_title} desc={_desc}></Content>
</div>
);
}
}
export default App;
728x90