728x90
클릭 시 state값을 변경하고 싶은 상황
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 ...'},
{id:2, title: 'css', desc:'css is ...'},
{id:3, title: 'javaScript', desc:'js is ...'}
]
}
}
render(){
console.log('lendering');
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;
}
return (
<div className="App">
{/* <Subject title={this.state.subject.title}
sub={this.state.subject.sub}></Subject> */}
<header>
<h1><a href="/" onClick={function(e){
console.log(e);
e.preventDefault();
this.state.mode = 'welcome';
}}>{this.state.subject.title}</a></h1>
{this.state.subject.sub}
</header>
<Subject title="react" sub="for ui"></Subject>
<TOC data={this.state.contents}></TOC>
<Content title={_title} desc={_desc}></Content>
</div>
)
};
}
이 코드는 state에 있는 mode:'read'를 header 태그의 title을 클릭했을 때 'welcome'으로 바꿔주려는 코드이다.
코드상 문제 없어보이지만 이대로 서버를 돌려보면,
이런 에러가 난다.
이유는
onClick={function(e){
console.log(e);
e.preventDefault();
this.state.mode = 'welcome';
}}
이 함수 안에서 this를 사용했는데 여기서는 this를 찾기 못하기 때문이다.
그럼 어떻게 우리가 설정해놓은 state를 접근할 수 있을까
먼저 저 함수가 this를 알게하려면 함수 뒤에 .bind(this)를 붙여야한다.
그러면 이 함수의 this를 지정해주는 것인데 그렇다고 저렇게 state에 접근하는 방법은 또 아니다.
이미 컴포넌트가 생성된 다음 동적으로 state값을 변경하고 싶을 때 this.setState() 함수를 만들어야한다.
그 이유는 this.state.mode 이런식으로 바꾸면 리액트 입장에서는 리액트 모르게 값이 바뀌기 때문에 렌더링을 할 수가 없는 것이다.
bind와 setState를 사용한 코드이다.
onClick={function(e){
console.log(e);
e.preventDefault();
// this.state.mode = 'welcome';
this.setState({
mode:'welcome'
})
}.bind(this)}
이런식으로!
그러면
처음 페이지 로드시 mode가 가르키는건 read지만
WEB을 클릭했을 때
페이지를 새롭게 로드하는 것이 아니라, 콘솔창에 에러 없이, mode를 welcome으로 변경할 수 있다.
state값을 바꿔서 밑에 HTML이 welcome으로 바꿀 수 있었다.
728x90
'FrontEnd > react' 카테고리의 다른 글
[react] shouldComponentUpdate (0) | 2023.02.02 |
---|---|
[react] State (4) | 2022.12.28 |
[react] Props 기초 (6) | 2022.12.27 |
[react] 컴포넌트 만들기 (4) | 2022.12.27 |
[react] 리액트 설치 (4) | 2022.12.27 |