React - multiple statement

React - multiple statement

React - if문이 많을 때 스타일 리턴해주기

Why

하나 혹은 둘까지는 render()에서 클래스나 스타일을 사용하면 할 수 있는데… if문이 여러 가지로 사용할 때 그 분기에 맞춰서 클래스나 스타일을 사용하려면 따로 함수로 빼서 값을 리턴받는 게 더 쉽다.

How

<article
    style={{paddingTop: this.articleHeight() + 'px'}}   // this
    className={cn([
        rootStyle.textWrap,
        this.state.showText && rootStyle.textShow,
        // this.props.uiState.showBanner ? rootStyle.textWrapBannerPadding : rootStyle.textWrapPadding
    ])}
>
...
</article>
articleHeight() {
    const showBanner = this.props.uiState.showBanner;

    if (this.state.started) {
        if (window.innerWidth > 1100) {
            return 0
        }
        return 90
    } else {
        if (showBanner) {
            return 202
        } else {
            return 90
        }
    }
}

주의

jsx에 !important를 추가로 붙이면 이 코드는 작동하지 않는다…

댓글

가장 많이 본 글