
React는 이전 트리를 버리고 완전히 새로운 트리를 구축
이전 DOM 노드를 모두 파괴하며(이전 트리와 연관된 state 모두 사라짐)
componentWillUnmount()실행
새로운 트리가 만들어짐 -> 새로운 DOM 노드들이 DOM에 삽입
동일한 내역은 유지하고 변경된 속성들만 갱신
예시로 살펴보자
<div className='before' title='stuff'/>
<div className='after' title='stuff'/>
위 예시에서 className만 변경됨
key를 통해 기존 트리와 이후 트리의 자식이 일치하는 지 확인
- 포커스, 텍스트 선택 영역, 미디어의 재생 관리
- 애니메이션 직접적으로 실행하기
- 서드 파티 DOM 라이브러리를 React와 같이 사용
React.createRef()를 통해 생성되고 ref 어트리뷰트를 통해 엘리먼트에 부착
예시로 살펴보자
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
} render() {
return <div ref={this.myRef} />;
}
}
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"/>은 사용자만이 값을 설정 가능, 따라서 항상 비제어 컴포넌트임