state

김세주·2021년 2월 18일
0

react

목록 보기
3/8

state 를 변경하려면 setState 를 사용한다
this.setstate({ mode : 'welcome' }) 이러면 모드를 웰컴으로 바꾼다 라는 뜻
this.setstate = 'welcome' 이런식으로 사용하면 안됨. this.setstate({mode:~~}) 이런식으로 함수형으로 작성해야 한다!! 값을 객체 형태로 주는 것을 통해 고쳐야함 ( 리액트가 파악을 해서 렌더 할 수 있도록 )
항상 스테이트 값이 바뀌면 setState 로 바꿔준다. 컨스트럭터안에서 맘대로 바꾸는 한이 있을지라도

<header>
          <h1>
            <a
              href="/"
              onClick={(e) => {
                console.log(e);
                e.preventDefault();
                this.setState({
                  mode: "welcome",
                });
              }}
            >
              {this.state.subject.title}
            </a>
          </h1>
          {this.state.subject.sub}
        </header>

이제 event를 만들어보자

이렇게 onChange를 써서 바꿔줄수 있는데 이떄 Subject컴포넌트로 가서

return (
      <div className="App">
        <Subject
          title={this.state.subject.title}
          sub={this.state.subject.sub}
          onChangePage={() => {
            alert("hihihi");
          }}
</Subject>
        {/* <header>
          <h1>
            <a
              href="/"
              onClick={(e) => {
                console.log(e);
                e.preventDefault();
                this.setState({
                  mode: "welcome",
                });
              }}

              {this.state.subject.title}
            </a>
          </h1>
          {this.state.subject.sub}
        </header> */}

onClick={(e)=>{
e.preventDefault();
this.props.onChangePage();}} 이렇게 해주면 App.js 를 렌더할떄 서브젝트 컴포넌트가 렌더가 되는데 그때 온체인지페이지가 렌더가 되는데 그건 App.js 에서 앨러트 해줄 수 있다.

import React, { Component } from "react";
class Subject extends Component {
  render() {
    console.log("Subject render");
    // function 생략
    return (
      <header>
        <h1>
          <a
            href="/"
            onClick={(e) => {
              e.preventDefault();
              this.props.onChangePage();
            }}
          >
            {this.props.title}
          </a>
        </h1>
        {this.props.sub}
      </header>
    );
  }
}
export default Subject;
profile
시간은 내 편이다.

0개의 댓글