-
Notifications
You must be signed in to change notification settings - Fork 3
6. Form
forjjy edited this page Nov 30, 2016
·
11 revisions
React 에서의 Form은 HTML의 Form과 비슷합니다. 하지만, 아래 코드는 실행하면 Input 필드에 값이 입력되지 않습니다.
var Text = React.createClass({
getInitialState() {
return {
textValue: "initial value"
};
},
render() {
return (
<div>
<p>{this.state.textValue}</p>
<input type="text" value={this.state.textValue} />
</div>
);
}
});
ReactDOM.render(
<Text />,
document.getElementById('root')
);
This form has the default HTML form behavior of browsing to a new page when the user submits the form. If you want this behavior in React, it just works. But in most cases, it's convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called "controlled components".
Controlled Component는 State에 따라 값을 관리하는 Componenet 입니다.(single source of truth) 위에서 입력되지 않는 부분을 아래처럼 setState를 이용하여 입력값이 반영될 수 있게 수정한 코드입니다.
var Text = React.createClass({
getInitialState() {
return {
textValue: "initial value"
};
},
changeText(e) {
this.setState({textValue: e.target.value});
},
render() {
return (
<div>
<p>{this.state.textValue}</p>
<input type="text" value={this.state.textValue} onChange={this.changeText} />
</div>
);
}
});
ReactDOM.render(
<Text />,
document.getElementById('root')
);
value를 State로 관리하고, onChange()에서 setState()하여 명시적으로 값을 갱신하고 전달합니다.