클래스형 컴포넌트
2021. 10. 21. 00:11ㆍReact/문법
- 클래스형 컴포넌트(함수형 컴포넌트와 Hooks 지원으로 현재는 잘 사용하지 않는 형태)
- render() 메서드 필수, 렌더링하고 싶은 JSX 를 반환
- props 를 조회 해야 할 때에는 this.props 를 조회
- 클래스 내부에 종속된 함수인 메서드, 커스텀 메서드는 보통 이름을 handle... 으로 명명
- 메서드들을 이벤트로 등록하게 되는 과정에서 각 메서드와 컴포넌트 인스턴스의 관계가 끊겨버리기 때문에 조치 필요
1. 첫번째는 클래스의 생성자 메서드 constructor 에서 bind 작업(가장 일반적)
class Counter extends Component {
constructor(props) {
super(props);
this.handleIncrease = this.handleIncrease.bind(this);
this.handleDecrease = this.handleDecrease.bind(this);
}
handleIncrease() {
console.log('increase');
console.log(this);
}
...
}
2. 커스텀 메서드를 선언 할 때 화살표 함수 문법을 사용해서 작성(단, CRA 로 만든 프로젝트에는 적용이 되어있는 문법이기 때문에 바로 사용 할 수 있습니다.)
class Counter extends Component {
handleIncrease = () => {
console.log('increase');
console.log(this);
};
handleDecrease = () => {
console.log('decrease');
};
...
}
3. onClick 에서 새로운 함수를 만들어서 전달(렌더링 할 때마다 함수가 새로 만들어지기 때문에 나중에 컴포넌트 최적화 할 때 까다롭습니다.)
return (
<div>
<h1>0</h1>
<button onClick={() => this.handleIncrease()}>+1</button>
<button onClick={() => this.handleDecrease()}>-1</button>
</div>
);
- 상태는 constructor 내부에서 this.state 를 설정, 무조건 객체형태여야 하며 this.state로 조회(화살표 함수 문법을 사용하여 메서드를 작성 할 수 있게 해줬던 class-properties 문법이 적용되어 있다면 굳이 constructor 를 작성하지 않고도 다음과 같이 state 를 설정해줄 수 있습니다.)
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
fixed: 1,
updateMe: {
toggleMe: false,
dontChangeMe: 1
}
};
}
handleIncrease = () => {
console.log('increase');
console.log(this);
};
...
}
// class-properties 문법 적용시(화살표 함수)
class Counter extends Component {
state = {
counter: 0
};
handleIncrease = () => {
console.log('increase');
console.log(this);
this.setState(state => ({ // 함수형 업데이트가 가능하며, 여러번 값을 변경해야할 때 유용
counter: state.counter + 1
}));
this.setState( // setState의 두번째 인자로 콜백함수를 넣어 값 변경 후 원하는 기능 수행 가능
{
counter: this.state.counter + 1
},
() => {
console.log(this.state.counter);
}
);
};
handleDecrease = () => {
console.log('decrease');
this.setState({ // setState로 업데이트 하며, 객체의 경우 불변성 유지해야 함
updateMe: {
...this.state.updateMe,
toggleMe: !this.state.updateMe.toggleMe
}
});
};
...
}
'React > 문법' 카테고리의 다른 글
CSS 문법 (0) | 2021.10.21 |
---|---|
Lifecycle Method (0) | 2021.10.21 |
Immer 라이브러리 (0) | 2021.10.20 |
Hooks - useContext (0) | 2021.10.20 |
Hooks - 커스텀 Hooks (0) | 2021.10.20 |