[생활코딩 React] ④ 이벤트

Glenn·2019년 11월 18일
0

[생활코딩]React

목록 보기
4/6

🎥 생활코딩 YouTube

1. 이벤트 state,props 그리고 rendor 함수

  • 🎁 이벤트 ?
    : 애플리케이션을 역동적으로 만들어주는 기술

👉 props, state, event 삼자가 서로 상호작용하면서 애플리케이션의 역동성을 만들기 때문에 같이 생각할 것!

class App extends Component {
  constructor(props) {//props, state의 값이 변경되면 화면이 다시 호출된다.
    super(props);
    this.state = {
      mode: "welcome",
      Subject: { title: 'WEB', sub: 'World Wid Web!' },
      welcome: { title: 'Welcome', desc: 'Hello, React!!' },
      contents: [
        { id: 1, title: 'HTML', desc: 'HTML is information' },
        { id: 2, title: 'Css', desc: 'Css is for design' },
        { id: 3, title: 'JavaScript', desc: 'JavaScript is for interactivs' }
      ]
    }
  }
  render() {//rendor()함수는 어떤 HTML을 그릴것인가를 결정하는 함수
    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>
        <TOC data={this.state.contents}></TOC>
        <Content title={_title} desc={_desc}></Content>
      </div>
    );
  }
}

export default App;

2. 이벤트 설치

render() { //어떤 HTML을 그릴것인가를 결정하는 함수
    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> */}
        <header>
          <h1><a href="/" onClick={function () {//링크를 클릭했을 때 실행되도록 약속되어있는 함수//JavaScript와는 다르게 onclick -> onClick
          }}>{this.state.Subject.title}</a></h1>
          {this.state.Subject.sub}
        </header>
        <TOC data={this.state.contents}></TOC>
        <Content title={_title} desc={_desc}></Content>
      </div>
    );
  }

3. 이벤트에서 state 변경하기 ( setState() )

return (
      <div className="App">
        {/* <Subject
          title={this.state.Subject.title}
          sub={this.state.Subject.sub}>
        </Subject> */}
        <header>
          <h1><a href="/" onClick={function (e) {//링크를 클릭했을때 실행되도록 약속되어있는 함수
            e.preventDefault();//이 태그가 가지고 있는 기본적인 명령어를 막을 경우 사용하는 코드//해당 값(state)을 변경하고 싶을 경우 this.setState를 사용해야 변경이 가능하다
            this.setState({
              mode: 'read'
            });
	     ⭐⭐⭐//컴포넌트 자체를 this로 사용할 경우 bind(this)를 넘겨주어야지만 
         ⭐⭐⭐//컴포넌트자체를 this로 인식이 가능하다.
          }.bind(this)}>{this.state.Subject.title}</a></h1>
          {this.state.Subject.sub}
        </header>
        <TOC data={this.state.contents}></TOC>
        <Content title={_title} desc={_desc}></Content>
      </div>
    );

4. 이벤트 bind 함수 이해하기

bind() : bind 함수는 ()내에 있는 객체를 function에 주입하는 함수이다.

//name이 glenn인 obj객체를 선언하자
var obj = {name:"glenn"};

//this의 name값을 출력하는 bindTest()함수를 선언하자
function bindTest(){
	console.log(this.name);
}

//여기서 bindTest()를 호출하면 어떠한 결과값이 나올까?
//'undefined'라는 값이 호출된다 => 선언된 this가 없으므로

//그렇다면 bind()함수를 사용하여 obj를 넘겨준다면?
var bindTest2 = bindTest().bind(obj);
bindTest2();
=> glenn

5. 컴포넌트 이벤트 만들기

1) 컴포넌트 나누기

  • 쉬운 코딩을 위해서 Subject.js 코드를 App.js로 가져와 코딩한 부분을 나누고, onChangePage라는 함수를 생성하여 연결하자
  • 기존 태그에 onChangePage 라는 함수를 연결하여 함수내에서 this.props.mode 의 값을 변경하는 코드를 입력한다.
  • Subject.js 내에서는 태그에 onClick 함수를 연결하여 페이지 이벤트를 제어하고 onChangePage를 호출한다.
  //App.js
return (
      <div className="App">
        <Subject
          title={this.state.Subject.title}
          sub={this.state.Subject.sub}
          ⭐onChangePage={function(){
            this.setState({mode:'welcome'});
          }.bind(this)}>
        </Subject>
        <TOC data={this.state.contents}></TOC>
        <Content title={_title} desc={_desc}></Content>
      </div>
    );

//Subject.js
return (
        <header>
          <h1><a href="/" ⭐onClick={function(e){
            e.preventDefault();
            this.props.onChangePage();
          }.bind(this)}>{this.props.title}</a></h1>
          {this.props.sub}
        </header>
      );

2) 컴포넌트 이벤트 적용하기

//App.js
return (
      <div className="App">
        <Subject
          title={this.state.Subject.title}
          sub={this.state.Subject.sub}
          onChangePage={function(){
            this.setState({mode:'welcome'});
          }.bind(this)}>
        </Subject>
        <TOC onChangePage={function(){//onChange 함수를 사용하여 mode값 변경
          this.setState({
            mode:'read'
          });
        }.bind(this)} 
        data={this.state.contents}></TOC>
        <Content title={_title} desc={_desc}></Content>
      </div>
    );

//TOC.js
while (i < data.length) {
            list.push(<li key={data[i].id}>
                <a href={"/content/" + data[i].id}
                    onClick={function (e) {//onClick 이벤트를 사용하여 onChangePage() 호출
                        e.preventDefault();
                        this.props.onChangePage();
                    }.bind(this)}>{data[i].title}</a></li>);
            i = i + 1;
        }

3-1) 속성을 이용하는 방법

//App.js
<TOC onChangePage={function (id) {//TOC.js에서 받아온 id값을 selected_content_id에 넘겨준다
          this.setState({
            mode: 'read',
            selected_content_id:Number(id)
          });
        }.bind(this)}
          data={this.state.contents}></TOC>

//TOC.js
while (i < data.length) {
            list.push(<li key={data[i].id}>
                <a href={"/content/" + data[i].id}
                    data-id={data[i].id}//받아올 값을 data-id에 넘겨준다
                    onClick={function (e) {
                        e.preventDefault();
                        this.props.onChangePage(e.target.dataset.id);//받은 값을 여기!에서 넘겨준다
                    }.bind(this)}>{data[i].title}</a></li>);
            i = i + 1;
        }

3-2) bind 함수를 이용하는 방법

//TOC.js
while (i < data.length) {
            list.push(<li key={data[i].id}>
                <a href={"/content/" + data[i].id}
                    ⭐data-id={data[i].id} 
                    ⭐onClick={function (id, e) {
                        e.preventDefault();
                        this.props.onChangePage(id); 
                    }.bind(this, data[i].id)}>{data[i].title}</a></li>);
            i = i + 1;
        }
profile
Front-end developer

0개의 댓글