반응형
Hoc vs Render 속성 값
컴포넌트에 공통적으로 사용되는 로직을 재사용 가능하도록 구현하는 방법에는 Hoc 와 Prop render 를 사용하는 2가지 방법이 있다.
1. 컴포넌트 내부 일부에서 적용하는 경우
HOC
현재 컴포넌트의 전체에 적용
//HOC
//로그인시에만 렌더링하는 HOC
const WithIsLogin = WrappedComponent =>
class WithIsLogin extends Component {
state = {
isLogin : false
}
checkIsLogin = ()=> {
/***/
}
componentDidMount(){
this.setState({ isLogin : this.checkIsLogin() })
}
render(){
if(this.state.isLogin){
return <WrappedComponent {...this.props}/>
}else{
return "로그인이필요합니다."
}
}
}
//사용
class ExampleComponent extends Component {
render(){
return (
<div>로그인하면 보임</div>
)
}
}
export default WithIsLogin(ExampleComponent)
현재 컴포넌트의 일부 render 를 제어 하는 경우
//IsLogin.js
const IsLogin = ({children})=>children
export default withIsLogin(IsLogin)
//사용
class ExampleComponent extends Component {
render(){
return (
<IsLogin>
<div>로그인하면 보임</div>
</IsLogin>
<div>로그인상관 없이 항상 rendering </div>
)
}
}
export default ExampleComponent
- wrapper 컴포넌트를 만들어야 한다.
Props Render
//IsLogin.js
class IsLogin extends Component {
state = {
isLogin : false
}
checkIsLogin = ()=> {
/***/
}
componentDidMount(){
this.setState({ isLogin : this.checkIsLogin() })
}
render(){
if(this.state.isLogin){
return this.props.children()
}else{
return "로그인이필요합니다."
}
}
//사용
class ExampleComponent extends Component {
render(){
return (
<IsLogin>
<div>로그인하면 보임</div>
</IsLogin>
<div>로그인상관 없이 항상 rendering </div>
)
}
}
export default ExampleComponent
반응형
'개발관련 > 리액트' 카테고리의 다른 글
[번역] 리액트 기술을 한 단계 업그레이드하세요: 2023년에 마스터할 고급 패턴 5가지 (0) | 2023.08.07 |
---|---|
리액트 컴포넌트 무한 스크롤 구현 (0) | 2023.05.11 |
CRA test 할때 axios import outside 에러 관련 (0) | 2023.05.01 |
React 프로젝트에서 GZIP 압축 사용하기 (0) | 2023.05.01 |
React-hook-form과 Material UI MUI Select Component 같이 사용 하는 방법 (0) | 2022.11.03 |