dev/react

react 이벤트

아디봉 2020. 5. 17. 01:27

참고사이트 

www.youtube.com/playlist?list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi

 

React - YouTube

 

www.youtube.com

2020/05/04 - [react/기초] - react 설치, 개발환경구축

2020/05/05 - [react/기초] - react 구조

2020/05/11 - [react/기초] - react 컴포넌트(component) 개념

2020/05/13 - [react/기초] - react 속성(props), react Developer Tools 사용

2020/05/15 - [react/기초] - react state소개 및 사용

- mode에 따라서 title(HTML영역)과 desc(HTML is for information 영역)이 틀려지는 예제

react 에서는 props값이나 state값이 바뀌면 해당되는 component의 render()함수가 다시 호출되게 되어있다.

즉 props나 state가 바뀌면 화면이 다시 그려진다.

import React, { Component } from 'react';
import Subject from "./components/Subject";
import Nav from "./components/Nav";
import Article from "./components/Article";
import './App.css';

class App extends Component {
  //state 초기화
  //컴포넌트가 실행될때 constructor이 있다면 제일먼저 실행되어서 초기화를 담당한다.
  constructor(props){
    super(props);
    //subject state값을 만듬
    this.state = {
      mode: 'welcome', //추가
      welcome: {title:'welcome', desc:'welcome react!'}, //추가
      subject:{title:'WEB', sub:'World Wide Web!'},
      contents:[
        {id:1, title:'HTML', desc: 'HTML is for information'},
        {id:2, title:'CSS', desc: 'CSS is for design'},
        {id:3, title:'JavaScript', desc: 'JavaScript is for interactive'},
      ]
    }
  }

  render(){
	//추가
    var _title, _desc = null;
    if (this.state.mode === 'welcome'){
      _title = this.state.welcome.title
      _desc = this.state.welcome.desc
    } else if (this.state.mode === 'read'){
      _title = this.state.contents[0].title
      _desc = this.state.contents[0].desc
    }

    return (
      <div className="App">
        <Subject 
          title={this.state.subject.title} 
          sub={this.state.subject.sub}>
        </Subject>
        <Nav data={this.state.contents}></Nav>
        <Article title={_title} sub={_desc}></Article> 
      </div>
    );
  }
}

export default App;

위처럼 state에 mode, welcome 을 추가 해주고, render()함수에 mode값에 따라서 분기처리 해준 후 

<Article 에 _title, _desc 코드로 바꿔준다.

개발자도구(f12)에서 app영역에 state mode값을 수동으로 바꿔주면서 테스트 할 수 있다.

mode가 welcome일때 
mode가 read일때

 

- react에서 이벤트 사용

import React, { Component } from 'react';
import Subject from "./components/Subject";
import Nav from "./components/Nav";
import Article from "./components/Article";
import './App.css';

class App extends Component {
  //state 초기화
  //컴포넌트가 실행될때 constructor이 있다면 제일먼저 실행되어서 초기화를 담당한다.
  constructor(props){
    super(props);
    //subject state값을 만듬
    this.state = {
      mode: 'welcome',
      welcome: {title:'welcome', desc:'welcome react!'},
      subject:{title:'WEB', sub:'World Wide Web!'},
      contents:[
        {id:1, title:'HTML', desc: 'HTML is for information'},
        {id:2, title:'CSS', desc: 'CSS is for design'},
        {id:3, title:'JavaScript', desc: 'JavaScript is for interactive'},
      ]
    }
  }

  render(){

    var _title, _desc = null;
    if (this.state.mode === 'welcome'){
      _title = this.state.welcome.title
      _desc = this.state.welcome.desc
    } else if (this.state.mode === 'read'){
      _title = this.state.contents[0].title
      _desc = this.state.contents[0].desc
    }

    return (
      <div className="App">
        {/* <Subject 
          title={this.state.subject.title} 
          sub={this.state.subject.sub}>
        </Subject> */}

        {/* subject를 component로 분리하지 않고 이벤트를 테스트하기 위해 subject.js에서 가져옴  */}
        <header>
            <h1><a href="/" onClick={function(e){
              console.log(e);
              e.preventDefault();
              alert('hi');
              // debugger 
            }}>{this.state.subject.title}</a></h1>
            {this.state.subject.sub}
        </header>
        <Nav data={this.state.contents}></Nav>
        <Article title={_title} sub={_desc}></Article>
      </div>
    );
  }
}

export default App;

subject.js에서 <header></header> 부분을 가져와서 클릭시 alert('hi') 창 생성됨 

- javascript 와 다르게 onClick(C가 대문자)로 사용된다.

- e.preventDefault(); 이벤트가 발생한 tag에 기본적인 동작을 막는다.

- debugger은 크롬 개발자도구에서 debugger을 만나면 실행을 멈춘 상태이다.

 

- bind() 함수

bind()함수 테스트

bindTest() 함수에 bind키워드로 obj객체를 bind시킬 수 있다.