[React] Input 다루기, ES 6 클래스
input 다루기
HTML
<div id="root"></div>
JS(Babel)
class App extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<div>
<MyForm name="홍길동"/>
</div>
);
}
}
class MyForm extends React.Component{
constructor(props){
super(props);
this.state = {
name: props.name
};
this.handleChange = ::this.handleChange;
this.handleSubmit = ::this.handleSubmit;
}
handleChange(event){
this.setState({
name: event.target.value
});
// state가 갖고 있는 name의 값을 바꾸겠다.
}
// 폼 전송 막기(엔터 시 초기화되는 문제 방지)
handleSubmit(event){
event.preventDefualt();
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<input type="text" value={this.state.name} onChange={this.handleChange.bind(this)}/>
<div>{this.state.name}</div>
</form>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
ES 6 클래스
JS(Babel)
console.clear();
class 동물{
constructor(이름,나이){
console.log(이름, 나이);
}
숨쉬다(){
console.log(this.이름 + '이(가) 숨쉽니다.');
}
}
// 상위 클래스에게 상속됨.
class 사람 extends 동물{
constructor(이름, 나이){
super(이름, 나이);
// 부모 생성자의 호출, 부모 생성자에게 매개변수를 넘기겠다.
// 동물에게 상속받음.
this.이름 = 이름;
this.나이 = 나이;
}
걷다(){
console.log(this.이름 + '이(가) 걷다.')
}
}
// 설계도
// 클래스는 변수와 함수로 이루어져 있음.
// props -> 매개변수.
const 김방울 = new 사람('김방울', 1);
// 설계도를 본따서 만들어짐
김방울.걷다();
const 야옹이 = new 사람('야옹이', 3);
야옹이.걷다();
야옹이.숨쉬다();