English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 장에서는 React에서 폼을 사용하는 방법을 배웁니다.
아래의 예제에서 입력 텍스트 필드를 설정합니다value = {this.state.data}
입력 값이 변경되면 상태를 업데이트할 수 있습니다. 이를 위해onChange
이벤트를 감시하고 상태를 업데이트하는 함수입니다. 입력 값이 변경되면 상태가 업데이트됩니다.
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({data: e.target.value}); } render() { return ( <div> <input type="text" value={this.state.data} onChange = {this.updateState} /> <h4>{this.state.data}</h4> </div> ); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/, document.getElementById('app'));
입력 텍스트 값이 변경될 때마다 상태가 업데이트됩니다.
아래의 예제에서 자식 컴포넌트의 텍스트 필드를 사용하는 방법을 볼 수 있습니다.onChange
메서드가 상태 업데이트를 유발하며, 이 상태 업데이트는 자식 입력value
화면에 표시합니다. 이벤트 장에서 유사한 예제가 사용되었습니다. 자식 컴포넌트의 상태를 업데이트하려면 항상 처리된 update()updateState
)의 함수를 prop로 사용합니다(updateStateProp
)전달됩니다。
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({data: e.target.value}); } render() { return ( <div> <Content myDataProp = {this.state.data} updateStateProp = {this.updateState}</Content> </div> ); } } class Content extends React.Component { render() { return ( <div> <input type = "text" value = {this.props.myDataProp} onChange = {this.props.updateStateProp} /> <h3>{this.props.myDataProp}</h3> </div> ); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/, document.getElementById('app'));
이렇게 되면 다음과 같은 결과가 나타납니다.