如何有条件地包装React组件? [英] How do I conditionally wrap a React component?

查看:50
本文介绍了如何有条件地包装React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,有时需要将其渲染为< anchor> ,而有时需要渲染为< div> .我读来确定的 prop this.props.url .

I have a component that will sometimes need to be rendered as an <anchor> and other times as a <div>. The prop I read to determine this, is this.props.url.

如果存在,则需要渲染包裹在< a href = {this.props.url}> 中的组件.否则,它只会呈现为< div/> .

If it exists, I need to render the component wrapped in an <a href={this.props.url}>. Otherwise it just gets rendered as a <div/>.

可能吗?

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

This is what I'm doing right now, but feel it could be simplified:

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

or, you can use a helper function to render the contents. JSX is code like any other. If you want to reduce duplications, use functions and variables.

这篇关于如何有条件地包装React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆