본문 바로가기

Web + APP/React

React Form과 bind 개념

반응형
SMALL

본 글은 아래 링크를 참고하여 만들었습니다.

https://ko.reactjs.org/docs/forms.html

 

폼 – React

A JavaScript library for building user interfaces

ko.reactjs.org


현재 React를 통해서 개인 프로젝트를 진행 중입니다. 아마 이번 달까지는 여러분들에게 보여줄 수 있을거라고 생각이 드네요 !! 대신 수면 시간을 줄겠지만 ㅠ

 

퇴근 후에도 코딩하는 기구한 인생...

 

사실 이 Form이라는 개념은 간단합니다.

 

한 번 살펴보죠.

<form action="/example_url">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" value="Submit">
</form> 

보통 html에 존재하는 form을 들고 왔습니다.

 

저기서 마지막 줄 input을 통해 버튼이 생기죠. (input이지만 Submit 버튼이 생성됩니다. 아마 type이 Submit이라서 그렇습니다)

 

이런 버튼

 

저 Submit을 누르면 화면이 redirect 되면서 (submit 종특이 redirect 시키는겁니다) input data가 전송이 되는 형식이죠.

 

 

간단하네요 그죠?


 

얘는 어떨까?

 

React에선 어떨까요? 우선 통째로 react 공식 자습서에 있는 애를 들고 왔습니다.

import React, { Component } from 'react';


class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

뭔가..

 

많죠

 

하나씩 뜯어봅시다.

import React, { Component } from 'react';


class NameForm extends React.Component {
  ...
  ...
}

얘의 경우엔 component를 정의한 것입니다. 함수 컴포넌트, class 컴포넌트가 있습니다. 여기에 렌더링할 html 코드를 작성하고 (정확히는 html 코드가 아닙니다. react에서 제공하는 html에서 보이는 코드입니다) data를 지지고 볶고 하시면 됩니다.

import React, { Component } from 'react';


class NameForm extends React.Component {
  ...
  ...
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

render라는 이름부터 감이 슬 오시죠. 얘가 html 코드로 변환이 되어서 사용자에게 보여주는 겁니다. 자세히 보면 {this.state.value}, {this.handleChange}라는 친구가 보이는데, 얘들이 어떤 애인지는 나중에 설명을 드리겠습니다.

import React, { Component } from 'react';


class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  ...
}

constructor(props)라는 메소드가 있습니다. 얘의 경우에 component가 불릴 때, 제일 처음 등장하는 실행되는 메소드가 constructor이며 이 contructor에서 react에서 다룰 변수 state를 초기화 시켜줘야합니다.

 

super(props)라고 있는데, 제 생각엔 이 컴포넌트가 부모로부터 데이터를 받았을 때, props로 받게 되는데, 그 때 부모로 받는 props가 super(props)가 아닐까 생각합니다. Vue에서 비슷한게 있었거든요.

 

아니면 댓글로 정정 부탁드립니다 !!

 
댓글에 Marshall K님께서 잘 설명을 해주셨습니다 !! 그 글을 참고하셔서 super(props)에 대해 이해를 하시면 될 것 같네요 !

state 앞에 붙어 있는 this는 자기 자신의 컴포넌트를 뜻하죠 !

 

그 밑에는 handleChange(event) / handleSubmit(event) 함수가 있습니다.

 

보면은 input에 onChange="this.handleChange"를 통해 작성 중인 data가 변할 때마다, state를 변화됩니다. 그리고 submit을 하면 alert이 뜨고, redirect를 막는 event.preventDefault()가 존재합니다.

 

여기까진 오케이! 쉽죠?

 

근데 여기서 제일 중요한 bind() 개념이 등장합니다.

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this); // 이 녀석과
    this.handleSubmit = this.handleSubmit.bind(this); // 요 녀석
  }
  ...
}

this로 바인딩을 해놨네요.

 

왤까요?

 

사실 저렇게 안하고 선언한 handleChange() 함수를 실행하면, 함수 안에서 가르키는 this컴포넌트 NameForm을 가리키지 못합니다. 그래서 window 자체를 가리키게 됩니다. (찾고, 찾고 하다가 제일 최상단으로 가버립니다)

 

그래서 !!! this.handleChange.bind(this)를 통해 'handleChange에서 선언될 this는 NameForm을 가리켜야 해!!!' 라고 말을 해주는거죠.

 

이렇게 안하고, handleSubmit(event) 함수 내부에서 console.log(this)를 하면 undefined 값이 뜹니다.

...
handleChange(event) {
	console.log(this) // undefined
}
...

저희는 NameForm을 가리키길 원하잖아요 그쵸 !?

 

보다 편하게 작성하시고 싶으시면 arrow function을 이용하시면 됩니다.

import React, { Component } from 'react';


class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  handleChange = (event) => {
    this.setState({value: event.target.value});
  }

  handleSubmit = (event) => {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  ...
}

이렇게 arrow function을 이용하는 것을 react에서도 권장하고 있습니다.

 

그러면 앞서 말했던 {this.state.value}, {this.handleChange} 이 친구들의 정체는 무엇일까요 !? 바로 Component 내에서 선언했던 함수와 변수들을 의미합니다. 이를 html 태그로 보이는 render() 함수 내에서 사용할 수 있습니다.

 

즉, 정의와 선언은 전부 Coponent 내부, 사용은 render 안에서 중괄호{}를 사용해서 사용자에게 보여주는 것입니다 !

 


이상 React Form과 bind 개념이었습니다. ^_^

반응형
LIST

'Web + APP > React' 카테고리의 다른 글

Flux 패턴  (0) 2021.03.19
React 소개 with 이벤트 위임  (4) 2021.03.16
이벤트 리스너 캐시  (0) 2021.03.14
React Project에 Tailwind 적용하기  (1) 2020.06.07