ReactJS映射:如何仅在url变量不为空时呈现html链接

ReactJS mapping: How do I render an html link ONLY when the url variable is not empty?

本文关键字:链接 html 变量 映射 何仅 url ReactJS      更新时间:2023-09-26

我有一个包含多个链接的产品列表。其中一个链接不是为我的所有产品填充的。

{ this.getSelectedProducts().map((product) => {
    const headerProductHtml = { __html: `Learn more about ${product.name}` };
    return (
        <div className="column swiper-slide" key={ `row-header-${product.id}` }>
            <div className="column__brand-background">
                <div className="column__brand-img">
                    <div className="column__brand-img-wrapper">
                        <img src={`/img/CornProductComparisonTool/logos/${product.id}_lg.png`} alt={product.name} />
                    </div>
                    <div className="column__urls">
                        <span className="column__url-learn" dangerouslySetInnerHTML={headerProductHtml}></span>
                        <a href={product.brandUrl}>View Details</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href={product.brandLabelUrl}>View Labels</a>           
                        {if (product.brandRatingsUrl){&nbsp;&nbsp;|&nbsp;&nbsp;<a href={product.brandRatingsUrl}>View Ratings</a>}}
                    </div>
                </div>
                <div className="column__close" onClick={this.onCloseClick.bind(this, product.id)}></div>
            </div>
        </div>     
    );  
}) } 

我添加的行是:

{if (product.brandRatingsUrl){&nbsp;&nbsp;|&nbsp;&nbsp;<a href={product.brandRatingsUrl}>View Ratings</a>}}

但它不起作用。我收到一个意外的令牌错误。这条线怎么了?

编辑:更改为这个,仍然不能工作

<a href={product.brandUrl}>View Details</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href={product.brandLabelUrl}>View Labels</a>
{product.brandRatingsUrl ? &nbsp;&nbsp;|&nbsp;&nbsp;<a href={product.brandRatingsUrl}>View Ratings</a> : null}

检查JSX中的If Else。

例如,您可以使用三元语句:

{ product.brandRatingsUrl ? <a href={product.brandRatingsUrl}>View Ratings</a> : null }

JSX中的大括号表示属性表达式(更多信息),这就是if语句被破坏的原因。尝试使用三元表达式:

{ product.brandRatingsUrl ? <a class="line-right" href={product.brandRatingsUrl}>View Ratings</a> : null }

此外,正如评论中所指出的,&nbps;不是有效的JS。为了在链接之前添加竖线,我会使用CSS(注意锚元素上的.line-right类):

.line-right:before {
  content: "|";
  margin-right: 5px;
  display: inline-block;
}