JS Tutorial - Basics of Form Handling

14839 단어 ReactReact

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

좋은 웹페이지 즐겨찾기