LifeCycleSample.js
import React, { Component } from 'react';
class LifeCycleSample extends Component {
state = {
number: 0,
color: null,
}
myRef = null;
constructor(props) {
super(props);
console.log('constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.color !== prevState.color){
return { color: nextProps.color };
}
return null;
}
componentDidMount(){
console.log('componentDidMount');
}
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate', nextProps, nextState);
return nextState.number % 10 !== 4 //숫자 마지막자리 4면 리렌더링 안함
}
componentWillUnmount(){
console.log('componentWillUnmount');
}
handleClick = () => {
this.setState({
number: this.state.number + 1
});
}
getSnapshotBeforeUpdate(prevProps, prevState){
console.log('getSnapShotBeforeUpdate');
if(prevProps.color !== this.props.color){
return this.myRef.style.color;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('componentDidUpdate', prevProps, prevState);
if(snapshot){
console.log('업데이트 되기 직전 색상: ', snapshot);
}
}
render() {
console.log('render');
const style = {
color: this.props.color
}
return (
<div>
<h1 style={style} ref={ref => this.myRef=ref}>
{this.state.number}
</h1>
<p>color: {this.state.color}</p>
<button onClick={this.handleClick}>
더하기
</button>
</div>
);
}
}
export default LifeCycleSample;
App.js
import React, { Component } from 'react';
import Mymemo from './Mymemo';
import './App.css';
import LifeCycleSample from './LifeCycleSample';
//랜덤 색상 생성
function getRandomColor(){
return '#' + Math.floor(Math.random() * 16777215).toString(16);
//16777215를 hex로 표현하면 ffffff가 되므로 000000 ~ ffffff 값 반환
}
class App extends Component {
state ={
color: '#000000'
}
handleClick = () => {
this.setState({
color: getRandomColor()
});
}
render() {
return(
<div>
<button onClick={this.handleClick}>랜덤 색상</button>
<LifeCycleSample color={this.state.color}/>
</div>
);
}
}
export default App;
버튼 렌더링 / 클릭 할때마다 handleRandomizeColor 메서드 호출되게 이벤트 설정
불러온 LifeCycleSample 컴포넌트에 color 값 props로 설정
'to be 개발자' 카테고리의 다른 글
리액트 공부 - launch chrome against localhost / 투두리스트 만들기 (0) | 2020.12.26 |
---|---|
리액트 공부 - js 스크롤바 css 설정 / component life cycle 흐름 / 투두 리스트 앱 기획 (0) | 2020.12.25 |
리액트 공부 - 더블 클릭시 삭제 handleRemove / 라이프사이클 메소드 (0) | 2020.12.25 |
리액트 공부 - map / input value 추가해서 아래 나타내기 (0) | 2020.12.25 |
리액트 공부 - 화살표함수 / 리액트이벤트 (종류) / onChange / onClick / state 예외 / ref (0) | 2020.12.24 |
댓글