ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React Forms
    카테고리 없음 2021. 12. 7. 17:40

    React에서의 Form element 사용법에 대해 정리하였습니다.



    < React Forms >

    Think about how forms work in a typical, non-React environment. A user types some data into a form’s input fields, and the server doesn’t know about it. The server remains clueless until the user hits a “submit” button, which sends all of the form’s data over to the server simultaneously.

    The problem is the period of time during which a form thinks that a user has typed one thing, but the server thinks that the user has typed a different thing. What if, during that time, a third part of the website needs to know what a user has typed? It could ask the form or the server and get two different answers. In a complex JavaScript app with many moving, interdependent parts, this kind of conflict can easily lead to problems.

     

    A traditional form doesn’t update the server until a user hits “submit.”
    But In a React form, you want the server to know about every new character or deletion, as soon as it happens.

     

    Example)

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    export class Input extends React.Component {
    	constructor(props) {
    		super(props);
    		this.state = { userInput: '' }; // 1
    		this.handleUserInput = this.handleUserInput.bind(this);
    	}
    
      handleUserInput(e) { // 2
        this.setState({ userInput: e.target.value})
      }
    
      render() {
        return (
          <div>
            <input type="text"
            onChange={this.handleUserInput} // 3
            value={this.state.userInput}/> // 4
            <h1>{this.state.userInput}</h1>
          </div>
        );
      }
    }
    
    ReactDOM.render(
    	<Input />,
    	document.getElementById('app')
    );

    1. The initial text should be blank!

    this.state = { userInput: '' };​

    2. Input Event Handler

    handleUserInput(e) {
    	this.setState({ userInput: e.target.value})
    }

    3. Input OnChange

    onChange={this.handleUserInput}

    4. Update Input's Value

    value={this.state.userInput}

    댓글

Designed by Tistory.