반응형
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
아래 링크를 통한 쿠팡 구매 시 블로그를 지속하는 큰 힘이 됩니다.
https://link.coupang.com/a/vB8Me
COUPANG
쿠팡은 로켓배송
www.coupang.com
"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
반응형
'개발관련 > 자바스크립트 팁' 카테고리의 다른 글
yarn2 ( yarn berry )와 함께 PnP(Plug'n'Play)를 적용해보기 고통스러운 node_modules 탈출 하기 (0) | 2022.09.15 |
---|---|
[JavaScript] encodeURI vs encodeURIComponent 의 차이 (0) | 2022.08.15 |
MUI 에서 차일드 선택하는 방법 mui styled child selector hover에서 선택하는 방법 (0) | 2022.07.20 |
MUI component에서 styled 사용하기 (0) | 2022.07.17 |
nvm 사용시 node 버전 기본값 변경 하기 (0) | 2022.07.12 |