7주차_react강의

보리·2022년 9월 19일
0

react 강의

목록 보기
2/8
post-thumbnail

리액트 공식문서로 공부하기

✏️ https://ko.reactjs.org/

#JSX란?

React에서는 본질적으로 렌더링 로직이 UI 로직(이벤트가 처리되는 방식, 시간에 따라 state가 변하는 방식, 화면에 표시하기 위해 데이터가 준비되는 방식 등)과 연결된다.

#엘리먼트 렌더링

  • 엘리먼트는 React 앱의 가장 작은 단위
  • 엘리먼트는 화면에 표시할 내용을 기술함.
const element = <h1>Hello, world</h1>;

#Components와 Props

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;
root.render(element);

#이벤트 처리하기

  • React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용함.
  • JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달함.
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Toggle />);

JavaScript에서 클래스 메서드는 기본적으로 바인딩되어 있지 않다. this.handleClick을 바인딩하지 않고 onClick에 전달하였다면, 함수가 실제 호출될 때 this는 undefined가 된다. 일반적으로 onClick={this.handleClick}과 같이 뒤에 ()를 사용하지 않고 메서드를 참조할 경우, 해당 메서드를 바인딩 해야 함.

profile
정신차려 이 각박한 세상속에서

0개의 댓글