dev/react

react 컴포넌트이벤트 만들기

아디봉 2020. 5. 19. 02:03

참고사이트 

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소개 및 사용

2020/05/17 - [react/기초] - 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
    }
    console.log('render', this);
    return (
      <div className="App">
        <Subject 
          title={this.state.subject.title} 
          sub={this.state.subject.sub}
          onChangePage={
            function(){
              //alert('hihihi');
              this.setState({mode: 'welcome'});
            }.bind(this)}
        >
        </Subject>

        <Nav data={this.state.contents}></Nav>
        <Article title={_title} sub={_desc}></Article>
      </div>
    );
  }
}

export default App;

App.js에 <Subject ... onChangePage처럼 사용자 함수를 만듬

 

- 사용자 정의함수 사용 

import React, { Component } from 'react';

class Subject extends Component {
    render(){
      return (
        <header>
            <h1><a href="/" onClick={function(e){
              e.preventDefault();
              this.props.onChangePage(); //사용자 정의함수 호출
            }.bind(this)}>{this.props.title}</a></h1>
            {this.props.sub}
        </header>
      );
    }
  }

export default Subject;

this.props.onChangePage()로 사용자 정의함수 호출함

 

 

- 목록 선택시 제목과 내용 바꿔주기 

App.js

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',
      selected_content_id: 2,
      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'){

      var i = 0;
      while(i < this.state.contents.length){
        var data = this.state.contents[i];
        if(this.state.selected_content_id === data.id){
          _title = data.title;
          _desc = data.desc;
          break;
        }
        i = i + 1;
      }
    }
    console.log('render', this);
    return (
      <div className="App">
        <Subject 
          title={this.state.subject.title} 
          sub={this.state.subject.sub}
          onChangePage={
            function(){
              //alert('hihihi');
              this.setState({mode: 'welcome'});
            }.bind(this)}
        >
        </Subject>

        <Nav 
          onChangePage={
            function(id){
              //alert('abc');
              this.setState({
                mode: 'read',
                selected_content_id: Number(id)
              });
            }.bind(this)
          }
          data={this.state.contents}></Nav>
        <Article title={_title} sub={_desc}></Article>
      </div>
    );
  }
}

export default App;

1. this.state에 selected_content_id 값 추가 

2. this.state.mode 가 read 일때 선택된 값(selected_content_id )과 데이터값(this.state.contents[i])이 같으면 데이터 설정해줌 

3. <Nav에 사용자 정의함수로 setState 값 설정

 

 

사용자 정의함수에 데이터 넘겨주는 방법1

Nav.js

import React, { Component } from 'react';

class Nav extends Component {
  render(){
    var lists = [];
    var data = this.props.data; //App.js state contents 값
    var i = 0;
    //while 반복문
    while(i < data.length){
      lists.push(<li key={data[i].id}>
        <a 
          data-id={data[i].id}
          href={"/content/"+data[i].id}
          onClick={function(e){
            e.preventDefault();
            this.props.onChangePage(e.target.dataset.id);
          }.bind(this)}
        >{data[i].title}</a></li>);
      i = i + 1;
    }
    return(
      <nav>
          <ul>
            {lists}
          </ul>
      </nav>
    );
  }
}

export default Nav;

<a 태그에 data-id={data[i].id} 설정해서 e 객체에서 e.target.dataset.id 를 사용 하는 방법 

 

 

사용자 정의함수에 데이터 넘겨주는 방법2

Nav.js

import React, { Component } from 'react';

class Nav extends Component {
  render(){
    var lists = [];
    var data = this.props.data; //App.js state contents 값
    var i = 0;
    //while 반복문
    while(i < data.length){
      lists.push(<li key={data[i].id}>
        <a 
          href={"/content/"+data[i].id}
          onClick={function(id, e){
            //debugger;
            e.preventDefault();
            this.props.onChangePage(id);
          }.bind(this, data[i].id)}
        >{data[i].title}</a></li>);
      i = i + 1;
    }
    return(
      <nav>
          <ul>
            {lists}
          </ul>
      </nav>
    );
  }
}

export default Nav;

bind() 함수에 파라미터 인자로 넘겨주게 되면 function(id, e) 처럼 첫번째 인자로 받아서 사용할 수 있다. 

만약 bind(this, data[i].id, 10) 처럼 하나더 넘겨주게 되면 function(id, num, e) 처럼 사용가능하다.