微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/js/152019.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐