제어 컴포넌트
리액트 폼 엘리먼트에서 사용자의 입력은 state에서 관리되고 setState로 변경된다
이때 state 신뢰 가능한 단일 출처(single source of truth)로 만들 수 있고 이때 컴포넌트가 사용자의 입력을 제어하면
이 컴포넌트는 제어 컴포넌트가 된다
class NameForm extends React.Component{
constructor(props) {
super(props);
this.state = {
value:''
}
this.handleInput = this.handleInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInput(e){
this.setState({
value: e.target.value
});
}
handleSubmit(e) {
alert(this.state.value);
e.preventDefault();
}
render() {
return (
<div>
<form action="" onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleInput}/>
<button>제출</button>
</form>
</div>
)
}
}
코드는 특별할게 없지만 input의 벨류값이 this.state에 의해서 onChange로 제어되고있다
'React' 카테고리의 다른 글
composition (0) | 2020.11.15 |
---|---|
state 끌어올리기 (0) | 2020.11.14 |
list, key (0) | 2020.11.06 |
조건부 렌더링 (0) | 2020.11.05 |
이벤트 처리하기 (0) | 2020.11.04 |