Sun's Blog

react 2일차 본문

ETC

react 2일차

버스는그만 2024. 1. 29. 23:58

이벤트 처리

JS와 유사하지만 아래와 차이가 있음

  • 카멜케이스 문법 사용
  • JSX 사용으로 문자열이 아닌 함수로 이벤트 핸들링
  • react에서는 return false 로 기본 동작을 방지할 수 없다. 오직 preventDefault 를 명시적으로 호출해야한다.

기존

<button onclick="action()">Button</button>

React

<button onclickk={action}>Button</button>

이벤트 등록

  • React 리스너를 추가하기 위해 addEventListener를 호출하는 대신 엘리먼트가 처음 렌더링될 때 리스너를 제공하면 된다.
  • JSX 콜백 안에서 this는 바인딩 되지 않으며 바인딩하지 않는 상태에서 this는 undefined가 된다.(React만이 아니라 JS 문법의 특징)
  • onClick={this.handleClick}과 같이 뒤에 ()를 사용하지 않고 메서드를 참조할 경우, 해당 메서드를 바인딩해야 한다.
  • 바인딩이 불편하다면 클래스 필드 문법이나 콜백에 화살표 함수를 사용하는 방법이 있다.

화살표

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // 이 문법은 `this`가 handleClick 내에서 바인딩되도록 합니다.
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}

조건부 렌더링

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

const root = ReactDOM.createRoot(document.getElementById('root'));

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isLoggedIn: false}
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true})
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false})
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;
    if(isLoggedIn) {
      button = <LogoutButton onClick={() =>this.handleLogoutClick()} />
    } else {
      button = <LoginButton  onClick={() =>this.handleLoginClick()} />
    }
    return  (
      <div>
        
        {button}
      </div>
    )
  }
}

function LoginButton(props) {
  return (
    <button onClick={() => props.onClick()}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={() => props.onClick()}>
      Logout
    </button>
  );
}

root.render(
  <React.StrictMode>
    <LoginControl />
  </React.StrictMode>
)
  • IF 절을 이용한 조건부 렌더링
  • IF-ELSE 구문은 condition ? true : false 로 표현
// IF-ELSE
render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}
  • 컴포넌트의 렌더링을 막고싶다면 return null값을 주면 된다.
import React from 'react';
import ReactDOM from 'react-dom/client';

const root = ReactDOM.createRoot(document.getElementById('root'));

function WarningBanner(props) {
  //렌더링 막기
  if(!props.warn) {
    return null;
  }

  return (
    <div className='warning'>
      Warning!
    </div>
  )
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {showWarning: true};
  }

  handleToggleClick() {
    this.setState(state => ({
      showWarning: !state.showWarning
    }))
  }

  render() {
    return (
      <div>
        <WarningBanner warn={this.state.showWarning} />
        <button onClick={() => this.handleToggleClick()}>
          {this.state.showWarning ? 'Hide' : 'Show'}
        </button>
      </div>
    )
  }
}

root.render(
  <React.StrictMode>
    <Page />
  </React.StrictMode>
)

'ETC' 카테고리의 다른 글

Tiles  (0) 2024.02.04
리액트 3일차  (0) 2024.01.31
React 1일차  (0) 2024.01.25
MyBatis에서 ENUM 다루기  (0) 2023.09.17
MicroService 간의 통신 방법  (0) 2023.08.26