⚛️ React/개념

React : 옛날 class문법

Zoeeey 2023. 5. 15. 20:49

class 문법으로 컴포넌트 만드는 법

class Modal2 extends React.Component {
  constructor(){
    super()
  }

  render(){
    return (
      <div>컨텐츠..</div>
    )
  }

}
  1. class 컴포넌트명 extends React.Component를 만든 후
  2. 그 안에 constructor, super, render 세 가지 함수를 넣는다.
  3. return 안에 축약할 html을 적는다

class 컴포넌트에서 state 만드는 법

class Modal2 extends React.Component {
  constructor(){
    super();
    this.state = {
      name : 'noran',
      age : 20
    }
  }

  render(){
    return (
      <div>내 이름은 {this.state.name}, {this.state.age}살이지.</div>
    )
  }

}
  1. constructor 안에 this.state라는 변수를 만들고 안에 object 형식으로 state를 나열한다.
  2. return 내에서 state를 사용할 때는 this.state.state명을 쓰면 된다.

class 컴포넌트에서 state 변경하는 법

class Modal2 extends React.Component {
  constructor(){
    super();
    this.state = {
      name : 'noran',
      age : 20
    }
  }

  render(){
    return (
      <div>내 이름은 {this.state.name}, {this.state.age}살이지.</div>
      <button
        onClick={()=>{this.setState({age : 21})
      }}>한살 더 먹기</button>
    )
  }

}
  • this.setState라는 기본함수를 쓴다.
  • state를 갈아치우는 건 아니다.

class 컴포넌트에서 props 이용하는 법

class Modal2 extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      name : 'noran',
      age : 20
    }
  }

  render(){
    return (
      <div>내 이름은 {this.props.props명}</div>
    )
  }

}

출처 : 코딩애플 https://codingapple.com/