개발관련/자바스크립트 팁

[React] Hoc와 render 속성 값 비교

개발자 Dane 2022. 8. 14. 12:39
반응형

Hoc vs Render 속성 값

컴포넌트에 공통적으로 사용되는 로직을 재사용 가능하도록 구현하는 방법에는 HocProp 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

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

반응형