[react] 생명주기 메서드를 이용하여 모바일 뷰와 데스크톱 뷰의 차이를 처리하는 방법은 무엇인가요?
1. componentDidMount
및 componentWillUnmount
활용
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { isMobileView: false };
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize() {
if (window.innerWidth < 768) {
this.setState({ isMobileView: true });
} else {
this.setState({ isMobileView: false });
}
}
render() {
const { isMobileView } = this.state;
return (
<div>
{isMobileView ? <MobileViewComponent /> : <DesktopViewComponent />}
</div>
);
}
}
export default MyComponent;
위의 예시에서 componentDidMount
에서 윈도우 리사이즈 이벤트를 감지하고, 이벤트 핸들러를 통해 화면 너비에 따라 모바일 뷰와 데스크톱 뷰를 구분하고 있습니다.
2. 미디어 쿼리 사용
또 다른 방법은 CSS 미디어 쿼리를 사용하여 반응형 디자인을 구현하는 것입니다.
/* index.css */
@media only screen and (max-width: 767px) {
// 모바일 스타일
}
@media only screen and (min-width: 768px) {
// 데스크톱 스타일
}
React에서는 위의 CSS를 컴포넌트 스타일로 가져와 사용할 수 있습니다.
3. 조건부 렌더링
마지막으로는 조건부 렌더링을 통해 화면의 너비를 확인하고 모바일 뷰와 데스크톱 뷰를 구분하여 처리할 수 있습니다.
import React from 'react';
const MyComponent = () => {
const isMobileView = window.innerWidth < 768;
return (
<div>
{isMobileView ? <MobileViewComponent /> : <DesktopViewComponent />}
</div>
);
}
export default MyComponent;
이러한 방법들을 통해 React 앱에서 모바일 뷰와 데스크톱 뷰 간의 차이를 처리할 수 있습니다.