TIL 13| [React] state&props

kim seung chan·2021년 8월 21일
0

Component & State & Props

state란 컴포넌트의 상태 값이다. stateprops는 둘 다 화면에 보여줄 정보를 가지고 있다는 점에서 서로 비슷한 역활을 한다. props는 컴포넌트는 사용하는 부모쪽에서 전달해야만 사용할 수 있고, state는 컴포넌트 내에서 정의하고 사용한다.

class App extends React.Component{
  
  constructor(props){
    super(props);

    this.state = {
      background: "blue",
      true: true,
    }

    onclick = () =>{
      if(this.state.true === true){
        this.setState({background: "red" , true: false 
      });
      }
      else if(this.state.true === false){
        this.setState({background: "blue" , true: true
      });
      }
    }
  }

  render(){
    return(
      <div>
         <Color background={this.state.background}
            onclick = {this.onclick}
        />
      </div>
    );
  }
}
  • click하면 background 값을 this.setState() 함수로 state를 업데이트 할 수 있다.
  • onClcik를 가지고 있는 컴포넌트인 button를 클릭할때 마다 색깔을 바꿔준다.

Color component 코드


function Color({background, onclick, img}) {
    return(
      <div>
            <div style={{color: background, 			       backgroundColor:img}}>Hello</div>
            <button onclick={onclick}>버튼</button>
      </div>
    );
}

export default Color;

props와 state

<Color />에 props인 background와 onClcik이라는 이름을 추가하여 props 값을 컴포넌트로 전달 하였다.

constructor()

constructor은 class의 instance가 생성될 때 항상 호출되는 함수 이다. 초기화할 값들을 constructor에서 세팅해준다.

super()라는 키워드는 꼭 작성해주어야 React.Component class에 있는 메서드들(ex.render)을 사용할 수 있다.

0개의 댓글