All Articles

REACT ing2

react에서 event, data를 사용해보며

handleInputEmail = (e) => {
    this.setState({
      email: e.target.value,
    });
  };

  handleInputPw = (e) => {
    this.setState({
      pw: e.target.value,
    });
  };

<input
    type="text"
    placeholder="Phone, email, or username"
    className="inputEmail"
    onChange={this.handleInputEmail}
    />
<input
    type="text"
    placeholder="Password"
    className="inputPw"
    onChange={this.handleInputPw}
    />

위와 같이 이벤트 핸들러가 같은 동작을 할 경우 처음엔 각각의 input 요소
그리고 state인 email과 pw로 인해 1개의 이벤트 핸들러에서는 email state를,
다른 1개의 이벤트 핸들러에서는 pw state를 다뤘다.
하지만 갱신해줘야하는 데이터(입력요소의 값)를 받을 대상이 다를 뿐이지 결국에는
데이터를 가지고 갱신하는 일은 같은 것이다.

위 코드를 이렇게 수정할 수 있겠다.
2개의 이벤트 핸들러를 1개로 줄이고 각각의 input 요소에서 사용할 수 있게한다.

handleInput = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

<input
    type="text"
    name="email"
    placeholder="Phone, email, or username"
    className="inputEmail"
    onChange={this.handleInput}
    />
<input
    type="text"
    name="pw
    placeholder="Password"
    className="inputPw"
    onChange={this.handleInput}
    />

어떻게 이런게 가능한 것일까??
이벤트 핸들러는 이벤트 객체를 받을 수 있는데 그 이벤트 객체는 이벤트를 일으킨
요소다.
즉 해당 요소에서 이벤트가 발생하면 [e.target.name]은 name을 email 또는
pw 구분한다.
name이 email인 요소면 email: e.target.value가 되는것이고
name이 pw인 요소면 pw:e.gartget.value가 되는것이다.

중복을 줄일 수 있는 정말 좋은 방법이다!