반응형
<"리액트를 다루는 기술" 책 참조>
React 책을 보다가 "Babel의 transform-class-properties" 문법이라는 문장이 나와서 Babel이 무엇인지 찾아보았습니다.
Babel(바벨) 이란?
Babel 공식 페이지 (https://babeljs.io/docs/en)에서는 이렇게 정의하고 있습니다.
Babel is a JavaScript compiler - (바벨은 자바 스크립트 컴파일러입니다)
인터프리터 언어에서 컴파일러가 필요할까?
- babel은 javascript로 결과물을 만들어주는 컴파일러.
* 왜 javascript로 변화할까?
- 새로운 기술을 가지지 않는 브라우져가 사용할 수 있게 변경해줌.
* 인터프리터란?
- 고급 언어로 작성된 프로그램을 한 줄 단위로 받아들여 번역하고, 번역과 동시에 프로그램을 한 줄 단위로 즉시 실행시키는 프로그램.
- 즉 소스코드를 한줄 한 줄씩 읽어 들이면서 실행하는 프로그램. (번역과 실행이 동시에 일어남)
Babel의 transform-class-properties 문법 예제
constructor (생성자)에 있는 bind 처리.
* bind를 안하게 되면?
- bind 줄을 지우고 실행을 하면 TypeError를 받을 수 있습니다. onClick이 handleClick을 호출할 때 this가 선언되지 않아 발생하는 문제.
this.handleChange = this.handleChange.bind(this);
- 지저분함.
- 코드량이 늘어남.
- 함수를 추가, 삭제 할 경우 생성자도 같이 수정해주어야 함.
해당 문법을 사용하여 간단하게 처리
import React, {Component} from 'react';
class EventPractice extends Component {
state = {
message : ''
}
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(e) {
this.setState({
message : e.target.value
});
}
handleClick = () => {
alert(this.state.message);
this.setState({
message : ''
});
}
render() {
return (
<div>
<h1>이벤트 연습</h1>
<input
type = "text"
name = "message"
placeholder = "아무거나 입력해 보세요"
value = {this.state.message}
onChange = {this.handleChange}
/>
<button onClick = {this.handleClick}>확인</button>
</div>
);
}
}
export default EventPractice;
import React, {Component} from 'react';
class EventPractice extends Component {
state = {
message : ''
}
handleChange = (e) => {
this.setState({
message : e.target.value
});
}
handleClick = () => {
alert(this.state.message);
this.setState({
message : ''
});
}
render() {
return (
<div>
<h1>이벤트 연습</h1>
<input
type = "text"
name = "message"
placeholder = "아무거나 입력해 보세요"
value = {this.state.message}
onChange = {this.handleChange}
/>
<button onClick = {this.handleClick}>확인</button>
</div>
);
}
}
export default EventPractice;
반응형
'JavaScript > React' 카테고리의 다른 글
일정 관리 웹 어플리케이션 만들기 (1) (0) | 2020.08.06 |
---|---|
Window VS Code 설치(Visual Studio Code) (0) | 2020.08.01 |
React 컴포넌트 (0) | 2019.12.02 |
Additional logging details can be found in : /npm-debug.log (0) | 2019.11.28 |
React 프로젝트 생성 (2) | 2019.10.05 |