React 실전 활용

woom·2023년 6월 28일
0

React

목록 보기
8/9
post-thumbnail

출처 : 패스트캠퍼스 한 번에 끝내는 프론트엔드 개발 초격차 패키지


📕 HOC (고착컴포넌트)

  • HOC(Higer Order Component): 컴포넌트 안에있는 로직을 재활용할 수 있는 advanced technique

    • React API와 관련 없음(리액트로 만들어진 컴포넌트를 사용할 뿐)
    • 리액트에서 컴포넌트를 조합 방식으로 하는 패턴
    • 컴포넌트를 인자로 받아 새로운 컴포넌트를 리턴하는 함수
    • HOC = function(컴포넌트) {return 새로운 컴포넌트;}
  • 사용하는 법

    • Cross-Cutting Concerns(횡단 관심사) : 여러 페이지에서 같은 일을 하는 것
    • 인자로 들어가는 컴포넌트를 변경하지 않음 (구성품처럼 사용)

📌 엘리먼트의 '상태'를 누가 관리하느냐

🐣 Controlled : 엘리먼트를 가지고 있는 컴포넌트가 관리(input, textarea, select)

  • 매번 state가 변경되는 상황에 UI를 함께 변경하고 싶은 경우에 사용
    • ex. 이메일이 일치하면 초록색, 불일치하면 빨간색

🐣 Uncontrolled : 엘리먼트의 상태를 관리하지 않고, 엘리먼트의 참조만 컴포넌트가 소유

  • 이벤트(ex. mouseover)에 맞춰 실제 HTML태그(element)에 포커스를 주는 경우에 사용
    • ex. 마우스를 올렸을때 단어에 포커스되게 하고 싶은경우

📙 Controlled Component

  • 엘리먼트를 가지고 있는 컴포넌트가 관리
import React from "react";

class ControlledComponent extends React.Component {
  state = {
    value: "",
  };
  render() {
    const { value } = this.state;
    return (
      <div>
        <input value={value} onChange={this.change} />
        <button onClick={this.click}>전송</button>
      </div>
    );
  }

  change = (e) => {
    this.setState({ value: e.target.value });
  };

  click = () => {
    console.log(this.state.value);
  };
}

export default ControlledComponent;

📒 Uncontrolled Component

  • 상태값을 보관할 ref 필요 inputRef = React.createRef();
  • render가 되는 시점에 ref에 저장해 놓고 필요할때 꺼내서 사용
import React from "react";

class UncontrolledComponent extends React.Component {
  inputRef = React.createRef();

  render() {
    console.log("initial render", this.inputRef);//current:null
    return (
      <div>
        <input ref={this.inputRef} />
        <button onClick={this.click}>전송</button>
      </div>
    );
  }

  componentDidMount() {
    console.log("componentDidMount", this.inputRef);
    //current:input
  }

  click = () => {
    console.log(this.inputRef.current.value);
  };
}
export default UncontrolledComponent;

profile
Study Log 📂

0개의 댓글

관련 채용 정보