생활코딩 react강의 4장

릿·2022년 3월 10일
0

생활코딩

목록 보기
2/4

4장 이벤트

이벤트 state props 그리고 render함수

render라는 함수의 기능이 props나 state의 값이 바뀌면 render함수가 호출되도록 약속되어 있다.

debugger

debugger 라고 되있는 부분에서 실행을 멈추고 sources에서 여러가지 정보를 얻을 수 있음.

e.preventDefault()

이벤트가 발생한 태그의 기본적인 동작방법을 못하게 막는 것. 즉, 페이지가 전환되지 않음.

bind()

  • bind = 묶어준다는 의미.
  • 기본적으로 render함수 안에서 컴포넌트 자체를 가리키기 때문에, 안의 함수는 this값이 아무 값도 없다. this값이 없을때 강제로 this값을 지정하는 방법이 bind이다.
  • 이벤트가 일어났을 때의 함수 안에서는 this가 자기 자신을 가리키지 않고 아무 값도 가리키지 않는다. 그럴 때는 a태그 속성에 .bind(this)를 추가해주면 된다.
    bind에 this를 하게되면 이 함수 안으로 주입하게 되어서 이 함수 안에서 this가 객체가 되게끔 하는 것이다.
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

setState함수

...
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>
)
profile
항상 재밌는 뭔가를 찾고 있는 프론트엔드 개발자

0개의 댓글