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是像任何其他代码.如果要减少重复,请使用函数和变量.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...