javascript – 如何有条件地包装一个React组件?

前端之家收集整理的这篇文章主要介绍了javascript – 如何有条件地包装一个React组件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个组件,有时需要被渲染为一个锚点,其他时候作为一个简单的div.这个prop.url道具,我触发了确定哪个是必需的.如果存在,我需要使用href = {this.props.url}将组件包装在锚点中.否则它只是被渲染为< div />.

可能?

这是我现在正在做的,但感觉可以简化:

if (this.props.link) {
    return (
        <a href={this.props.link} className={baseClasses}>
            <i className={styles.Icon}>
                {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是像任何其他代码.如果要减少重复,请使用函数和变量.

原文链接:https://www.f2er.com/js/152019.html

猜你在找的JavaScript相关文章