React(state) - 2

大 炫 ·2020년 8월 1일
0

react

목록 보기
2/8
post-thumbnail

state란?

App이란 클래스의 Component안에

  constructor(props){
    super(props);
    this.state = {
      mode:'welcome',
      subject:{title:'Web', sub:'World Wide Web!'},
      welcome:{title:'welcome', desc:'Hello, React !!'},
      contents :[{},{},{}]
    }
  }

이와같이 constructor(){ this.state = {} } 라고 정의되는데 이는 Component최상단에서 먼저 state를 정의하고 후에 어떤 html을 그릴것인가를 정의하는 render()함수를 호출할 때

  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()
    }

if()문을 써서 state안에 mode값이 onClick따위로 변경될때(다시 refresh됨으로 render()함수 재호출) 모드값에 따라 페이지의 내용을 변경하는 요소이다.
이런 render함수 재호출로 인해 refresh되는 이벤트들을 막는것으로는 preventDefault()함수가 있다.

state와 props의 차이점?

두 객체 모두 렌더링 결과물에 영향을 주는 정보를 갖고 있는데, 방식에서 차이가 존재한다. props는 (함수 매개변수처럼) Component에 전달되는 반면 state는 (함수 내에 선언된 변수처럼) Component 안에서 관리된다.

profile
대현

0개의 댓글

관련 채용 정보