IT박스

React 컴포넌트를 조건부로 래핑하는 방법은 무엇입니까?

itboxs 2020. 11. 28. 08:53
반응형

React 컴포넌트를 조건부로 래핑하는 방법은 무엇입니까?


때때로로 렌더링해야 할 구성 요소가 <anchor>있고 다른 시간에는 <div>. prop내가 이것을 결정하는 읽기입니다 this.props.url.

존재하는 경우 <a href={this.props.url}>. 그렇지 않으면 그냥 <div/>.

가능한?

이것이 제가 지금하고있는 일이지만 단순화 할 수 있다고 생각합니다.

if (this.props.link) {
    return (
        <a href={this.props.link}>
            <i>
                {this.props.count}
            </i>
        </a>
    );
}

return (
    <i className={styles.Icon}>
        {this.props.count}
    </i>
);

최신 정보:

다음은 최종 잠금입니다. 팁 주셔서 감사합니다, @Sulthan !

import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';

export default class CommentCount extends Component {

    static propTypes = {
        count: PropTypes.number.isRequired,
        link: PropTypes.string,
        className: PropTypes.string
    }

    render() {
        const styles = require('./CommentCount.css');
        const {link, className, count} = this.props;

        const iconClasses = classNames({
            [styles.Icon]: true,
            [className]: !link && className
        });

        const Icon = (
            <i className={iconClasses}>
                {count}
            </i>
        );

        if (link) {
            const baseClasses = classNames({
                [styles.Base]: true,
                [className]: className
            });

            return (
                <a href={link} className={baseClasses}>
                    {Icon}
                </a>
            );
        }

        return Icon;
    }
}

변수를 사용하십시오.

var component = (
    <i className={styles.Icon}>
       {this.props.count}
    </i>
);

if (this.props.link) {
    return (
        <a href={this.props.link} className={baseClasses}>
            {component}
        </a>
    );
}

return component;

또는 도우미 함수를 사용하여 콘텐츠를 렌더링 할 수 있습니다. JSX는 다른 것과 같은 코드입니다. 중복을 줄이려면 함수와 변수를 사용하십시오.


요소를 래핑하기위한 HOC (상위 구성 요소)를 만듭니다.

const WithLink = ({ link, className, children }) => (link ?
  <a href={link} className={className}>
    {children}
  </a>
  : children
);

return (
  <WithLink link={this.props.link} className={baseClasses}>
    <i className={styles.Icon}>
      {this.props.count}
    </i>
  </WithLink>
);

Here's an example of a helpful component I've seen used (not sure who to accredit it to) that does the job:

const ConditionalWrap = ({ condition, wrap, children }) => (
 condition ? wrap(children) : children
);

Use case:


<ConditionalWrap
  condition={Boolean(someCondition)}
  wrap={children => (<a>{children}</a>)} // Can be anything
>
 This text is passed as the children arg to the wrap prop
</ConditionalWrap>



You could also use this component: conditional-wrap

A simple React component for wrapping children based on a condition.


You should use a JSX if-else as described here. Something like this should work.

App = React.creatClass({
    render() {
        var myComponent;
        if(typeof(this.props.url) != 'undefined') {
            myComponent = <myLink url=this.props.url>;
        }
        else {
            myComponent = <myDiv>;
        }
        return (
            <div>
                {myComponent}
            </div>
        )
    }
});

You could also use a util function like this:

const wrapIf = (conditions, content, wrapper) => conditions
        ? React.cloneElement(wrapper, {}, content)
        : content;

There's another way you could use a reference variable

let Wrapper = React.Fragment //fallback in case you dont want to wrap your components

if(someCondition) {
    Wrapper = ParentComponent
}

return (
    <Wrapper parentProps={parentProps}>
        <Child></Child>
    </Wrapper>

)

참고URL : https://stackoverflow.com/questions/33710833/how-do-i-conditionally-wrap-a-react-component

반응형