React/ReactJS

2023/07/19__ReactJS(2)

HELLICAT 2023. 7. 19. 18:34
반응형

State

props

  • 부모 컴포넌트가 자식 컴포넌트에 값을 전달할 때 사용(읽기 전용)

state

  • 컴포넌트 자신이 가지고 있는 값
  • 컴포넌트 내부의 동적 데이터
  • 변화가 필요한 경우 setState()함수 사용

Constructor 작성

class App extends Component{
	constructor(props){ // method bind을 하거나 state를 초기화
    	super(props); //super를 사용해야 this가 사용된다.
        this.state={
        	subject:{title:'WEB', sub:'World Wide Web!'}
        }
   }
   render(){
   	....
   }
}

Constructor(생성자)

  • state(컴포넌트 상태) 값을 초기화하거나 메서드를 바인딩 할 때 사용
  • 해당 컴포넌트가 마운트 되기 전 호출
  • 함수방식에서는 사용불가

마운트

  • DOM 객체가 생성되고 브라우저에 나타나는 것을 의미

컴포넌트 라이프 사이클

  • 마운트 : DOM 객체 생성, 브라우저에 출력
  • Update : props값 변경, state 값 변경, 부모 컴포넌트 리렌더링
  • UnMount : 컴포넌트가 DOM에서 제거

메서드 바인딩

  • 클래스와 메서드 간의 연관 관계
  • 클래스와 연관된 메서드는 클래스에 바인딩 가능

super

  • React.Componet를 상속한 컴포넌트의 생성자를 구현할 때 다른 구문 앞에  super(props)를 호출하지 않으면 this.props가 생성자 내에서 정의 되지 않아 버그 발생

javascript에서의 super

  • 부모 클래스 생성자
  • constructor에서 super(props) 선언 전까지 this 사용 불가

Key props(여러 개의 데이터 사용)

//App.js
import {Component} from "react";

class App extends Component{
	constructor(props){ // method bind을 하거나 state를 초기화
    	super(props); //super를 사용해야 this가 사용된다.
        this.state={
        	subject:{title:'WEB', sub:'World Wide Web!'}
            contents:[
            	{id:1, title:'html', desc:'HTML is for infromation'},
                {id:2, title:'css', desc:'css for design'},
                {id:3, title:'javascrip', desc:'javascript is interactive'}
             ]
        }
   }
   render(){
		return{
        	<TOD data={this.state.contents} />
            }
   }
}



//TOD.js
import {Component} from "react";

class TOD extends Component {
  render() {
    const list = [];
    const data = this.props.data;
    let i = 0;
    for (; i < data.length; i++) {
      list.push(<li>{data[i].title}</li>);
      list.push(<li>{data[i].desc}</li>);
      list.push(<br />);
    }
    return (
      <nav>
        <ul>{list}</ul>
      </nav>
    );
  }
}

export default TOD;

이벤트

이벤트 state props와 render 함수

render 함수

  • react에서는 props나 state가 변경될 때마다 해당되는 컴포넌트의 render 함수 및 하위 컴포넌트의 render함수 호출

 

렌더링 테스트

  • App.js / Subject.js / TOD.js / Content.js 파일에 콘솔로그 작성 후 페이지 실행
  • [개발자 도구] - [콘솔] 탭에서 로그 확인

 

App.js

render(){
	console.log('App.js 렌더링 완료')
    }

이벤트 사용

  • mode 항목 작성하고 welcome일 때 사용할 데이터 추가
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: "welcome",
      subject: {title: "WEB", sub: "World Wide Web"},
      welcome: {title: "welcome", desc: "Hellow React"},
      contents: [
        {id: 1, title: "html", desc: "HTML is for infromation"},
        {id: 2, title: "css", desc: "css for design"},
        {id: 3, title: "javascrip", desc: "javascript is interactive"},
      ],
    };
  }
	render(){
    ....
    }
}

이벤트 작성

  • 요소에 직접 핸들러 작성 후 함수 작성
  • 다른 컴포넌트에 있는 링크로 현재 컴포넌트의 제어 방식 다름(*)
  • 현재 컴포넌트에 링크 사용 이해 후 다른 컴포넌트의 링크 사용 실습

javascript 이벤트 사용

  • onclick = '함수명'

react 이벤트 사용

  • react에서는 유사 html 사용(react 문법 준수)
  • onClick = {실행할 문장}
  • 이벤트 이름은 반드시 대문자 사용

링크에 이벤트 적용

  • 페이지 새로고침
  • 리액트의 장점 - 새로고침 없이 페이지 처리

해결방법

  • 이벤트를 실행한 객체 (요소, 태그)의 기본 동작을 제한
  <h1>
          <a
            href="#none"
            onClick={function (e) {
              alert("Hi!!!");
              e.preventDefault();
            }}
          >
            {this.state.subject.title}
          </a>
        </h1>
728x90