Javascript 如何有条件地包装 React 组件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33710833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:23:04  来源:igfitidea点击:

How do I conditionally wrap a React component?

javascriptreactjs

提问by Brandon Durham

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

我有有时需要被呈现为一个组件<anchor>和其他次为一<div>。在prop我读来确定这一点,是this.props.url

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/>.

如果存在,我需要渲染包裹在<a href={this.props.url}>. 否则它只会被渲染为<div/>.

Possible?

可能的?

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>
);

UPDATE:

更新:

Here is the final lockup. Thanks for the tip, @Sulthan!

这是最后的锁定。感谢您的提示,@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;
    }
}

回答by Sulthan

Just use a variable.

只需使用一个变量。

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;

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.

或者,您可以使用辅助函数来呈现内容。JSX 和其他代码一样。如果要减少重复,请使用函数和变量。

回答by Do Async

Create a HOC (higher-order component) for wrapping your element:

创建一个 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>
);

回答by antony

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>


回答by Avinash

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>

)

回答by Agu Dondo

You could also use this component: conditional-wrap

你也可以使用这个组件:conditional-wrap

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

一个简单的 React 组件,用于根据条件包装子级。

回答by Tomek

You could also use a util function like this:

您还可以使用像这样的 util 函数:

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

回答by user2027202827

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

您应该按照此处所述使用 JSX if-else 。像这样的事情应该有效。

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>
        )
    }
});