JS Tutorial - Basics of Form Handling
regular HTML
// App.js
import React from 'react';
import Form from './components/Form';
function App() {
return (
<div className="App">
<Form />
</div>
);
}
export default App;
// Form.js
import React, { Component } from 'react'
class Form extends Component {
render() {
return (
<form>
<div>
<label>Username</label>
<input type='text' />
</div>
</form>
)
}
}
export default Form
→ Controlled React Component
// Form.js
import React, { Component } from 'react'
class Form extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
comments: '',
topic: 'react'
}
}
handleUsername = event => {
this.setState({
username: event.target.value
})
}
handleCommentsChange = event => {
this.setState({
comments: event.target.value
})
}
handleTopicChange = event => {
this.setState({
topic: event.target.value
})
}
handleSubmit = event => {
alert(`${this.state.username} ${this.state.comments} ${this.state.topic}`)
event.preventDefault()
}
render() {
const {username, comments, topic} = this.state
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>Username</label>
<input type="text" value={username} onChange={this.handleUsername}/>
</div>
<div>
<label>Comments</label>
<textarea value={comments} onChange={this.handleCommentsChange}></textarea>
</div>
<div>
<lable>Topic</lable>
<select value={topic} onChange={this.handleTopicChange}>
<option value="react">React</option>
<option value="angular">Angular</option>
<option value="vue">Vue</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
)
}
}
export default Form
event.preventDefault()
submit & page refresh 후에 filled in data가 사라지는 form submission의 default behavior를 방지한다.
type="submit"
type="submit"
will give the user the ability to submit forms by hitting the enter key.
🔗 ReactJS Tutorial - 21 - Basics of Form Handling
Author And Source
이 문제에 관하여(JS Tutorial - Basics of Form Handling), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jheeju/ReactJS-Tutorial-Basics-of-Form-Handling저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)