[ React ] 리액트 공식 문서 - 재조정, Ref와 DOM, 비제어 컴포넌트

·2023년 8월 23일

재조정

비교 알고리즘

루트 엘리멘트 타입이 다른 경우

React는 이전 트리를 버리고 완전히 새로운 트리를 구축
이전 DOM 노드를 모두 파괴하며(이전 트리와 연관된 state 모두 사라짐)
componentWillUnmount() 실행
새로운 트리가 만들어짐 -> 새로운 DOM 노드들이 DOM에 삽입

DOM 엘리먼트 타입이 같은 경우

동일한 내역은 유지하고 변경된 속성들만 갱신

예시로 살펴보자

<div className='before' title='stuff'/>
<div className='after' title='stuff'/>

위 예시에서 className만 변경됨

keys

key를 통해 기존 트리와 이후 트리의 자식이 일치하는 지 확인

Ref와 DOM

Ref 사용이 필요할 때

  • 포커스, 텍스트 선택 영역, 미디어의 재생 관리
  • 애니메이션 직접적으로 실행하기
  • 서드 파티 DOM 라이브러리를 React와 같이 사용

Ref 생성하기

React.createRef()를 통해 생성되고 ref 어트리뷰트를 통해 엘리먼트에 부착

예시로 살펴보자

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  } render() {
    return <div ref={this.myRef} />;
  }
}

Ref 접근하기

render 안에서 ref가 전달되었을 때 그 노드를 향한 참조는 currnet 어트리뷰트에 담기게 됨

  • ref 어트리뷰트가 HTML 엘리먼트에 쓰임 ==> 생성자에서 React.createRef() 로 생성된 ref는 자신을 전달받은 DOM 엘리먼트를 current 프로퍼티 값으로서 받음
    예시로 살펴보자
class CustomTextInput extends React.Component {
  constructor(props){
    super(props);
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }
  focusTextInput(){
    this.textInput.current.focus();
    //text 타입의 input 엘리먼트에 focus
    // DOM 노드를 얻기 위한 current 프로퍼티에 접근
  }
  
  render(){
    return (
      <div>
      	<input type='text' ref={this.textInput} />
		<input type='button' value='Focus the text input' 
				onClick={this.focusTextInput} />
          </div>
		);
	}
}
  • ref 어트리뷰트ㅏ 커스텀 클래스 컴포넌트에 쓰임 ==> ref 객체는 마운트된 컴포넌트의 인스턴스를 current 프로퍼티 값으로 받음

예시로 살펴보자

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }
  
  componentDidMount(){
    this.textInput.current.focusTextInput();
  }
  
  render(){
    return (
      <CustomTextInput  ref={this.textInput} />
		);
	}
}
  • 함수 컴포넌트는 인스턴스가 없음 ==> 함수 컴포넌트에 ref 어트리뷰트 사용 불가
    따라서 useImperativeHandle 또는 클래스 컴포넌트로 변경하여 사용

비제어 컴포넌트

기본 값

비제어 컴포넌트를 사용하면 React 초깃값을 지정하지만 그 이후의 업데이트는 제어하지 않는 게 좋음 따라서 value 대신 defaultValue 지정 가능

파일 입력 태그

<input type="file"/> 은 사용자만이 값을 설정 가능, 따라서 항상 비제어 컴포넌트임

profile
new blog: https://hae0-02ni.tistory.com/

0개의 댓글