Language/React.js

[React] React Event

마탁이 2021. 1. 24. 21:20

1. React Event

 - HTML과 마찬가지로 React는 사용자 이벤트를 기반으로 작업을 수행할 수 있다.

 - React는 HTML과 동일한 이벤트를 가지고 있다. (e.g : click, change, mouseover 등)

 

2. Event 추가

 - React 이벤트는 camelCase 로 작성된다. (Upper Camel Case : 각 합성어의 첫 글자만 대문자로 표기하는 코딩 룰)

 - React 이벤트 핸들러는 중괄호 안에 작성된다.

// React
import React from 'react';
import ReactDOM from 'react-dom';

function shoot()
{
    alert("Great Shot!");
}

const myElement = (
    <button onClick={shoot}>Take the shot!</button>
);

ReactDOM.render(myElement, document.getElementById('root'));
// HTML
<button onclick="shoot()">Take the Shot!</button>

 

3. Event Handler

 - 컴포넌트 클래스의 메서드로 이벤트 핸들러를 배치하는 것이 좋다.

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends  React.Component
{
    shoot()
    {
        alert("Greate Shoot !");
    }

    render()
    {
        return(
            <button onClick={this.shoot}>Take the shot!</button>
        );
    }
}

ReactDOM.render(<Football />, document.getElementById('root'));

 

4. Bind this

 - React 함수의 경우 this 키워드는 함수를 소유하는 구성 요소를 나타내야한다.

 - 따라서 Arrow Func을 사용해야 한다.

   Arrow Func에서 this는 함수를 정의한 개체를 나타낸다.

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends  React.Component
{
    shoot = () => {
        alert(this);
    }

    render()
    {
        return(
            <button onClick={this.shoot}>Take the shot!</button>
        );
    }
}

ReactDOM.render(<Football />, document.getElementById('root'));

 * 일반함수에서 this 키워드는 전역 창 객체, HTML 단추 등을 포함한 함수를 호출한 개체를 나타낸다.

 

 - Arrow Func 대신 일반 함수를 사용해야 하는 경우 다음과 같이 bind()를 사용하여 바인딩한다.

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends  React.Component
{
    constructor(props)
    {
        super(props);
        this.shoot = this.shoot.bind(this)
    }
    shoot()
    {
        alert(this);
    }

    render()
    {
        return(
            <button onClick={this.shoot}>Take the shot!</button>
        );
    }
}

ReactDOM.render(<Football />, document.getElementById('root'));

 

5. 매개 변수 전달

 - 매개 변수를 이벤트 핸들러로 보내는 방법은 2가지가 있다.

  1. Arrow func

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
    shoot = (a) => {
        alert(a);
    }
    render() {
        return (
            <button onClick={() => this.shoot("Goal")}>Take the shot!</button>
        );
    }
}

ReactDOM.render(<Football />, document.getElementById('root'));

  2. this를 이용한 이벤트 핸들러

import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
    shoot(a) {
        alert(a);
    }
    render() {
        return (
            <button onClick={this.shoot.bind(this, "Goal")}>Take the shot!</button>
        );
    }
}

ReactDOM.render(<Football />, document.getElementById('root'));

 

 * bind()를 사용하지 않고 매개 변수를 전달하면(this.shoot.bind(this, "Goal") 대신 this.shoot(this, "Goal"))

  shoot 버튼이 클릭 될 때까지 기다리지 않고 페이지가 로드 될 때 함수가 실행된다.

 

6. React Event Object

 - 이벤트 핸들러는 함수를 Trigger 한 React 이벤트에 액세스할 수 있다.

 - Arrow Func를 사용할 때와 아닐 때 구문이 다르다.

// Arrow Func
import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
    shoot = (a, b) => {
      alert(b.type);
      /*
      'b' represents the React event that triggered the function,
      in this case the 'click' event
      */
    }
    render() {
      return (
        <button onClick={(ev) => this.shoot("Goal", ev)}>Take the shot!</button>
      );
    }
  }
  
  ReactDOM.render(<Football />, document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';

class Football extends React.Component {
  shoot = (a, b) => {
    alert(b.type);
    /*
    'b' represents the React event that triggered the function,
    in this case the 'click' event
    */
  }
  render() {
    return (
      <button onClick={this.shoot.bind(this, "Goal")}>Take the shot!</button>
    );
  }
}

ReactDOM.render(<Football />, document.getElementById('root'));

'Language > React.js' 카테고리의 다른 글

[React] NPM과 NPX, package-lock.json  (0) 2021.01.27
[React] JavaScript / React Binding  (0) 2021.01.24
[React] React 수명주기(Lifecycle)  (0) 2021.01.24
[React] React State  (0) 2021.01.24
[React] 컴포넌트 Prop  (0) 2021.01.24