簡體   English   中英

如何在React中的某些HTML中間有條件地包含標記

[英]How do I conditionally include a tag in the middle of some HTML in React

我有一個Avatar React組件,可以選擇是否鏈接到個人資料。 您可能不希望它鏈接到配置文件,例如,如果您在用戶配置文件上,而是您想要執行自定義clickHandler 有沒有更好的方法,除了在每個if和else鏈接之外只使用基本相同的HTML進行if / else? 下面是一些偽渲染代碼,只是為了展示我的意思:

 <div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
    {if (this.props.link) { 
      <Link to="profile" params={{userId:this.props.user.id}}>
     }
    }

      <img className="__avatarimage" src={this.props.user.avatar} />

    {if (this.props.link) {
      </Link> 
     }
    }
  </div>

使用:

<div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
{ this.props.link ?
  <Link to="profile" params={{userId:this.props.user.id}}>
    <img className="__avatarimage" src={this.props.user.avatar} />
  </Link>
  : <img className="__avatarimage" src={this.props.user.avatar} /> }

您可以嘗試通過先前定義img來消除img的雙重定義:

var img = <img className="__avatarimage" src={this.props.user.avatar} />;

並使用以下方法嵌入:

{img}

我創建了一個函數,它返回圖像或鏈接中包含的圖像,然后將其添加到div。

var createAvatar = function() {
  if (this.props.link) {
    return <Link to="profile" params={{userId:this.props.user.id}}>
      <img className="__avatarimage" src={this.props.user.avatar} />
    </Link>;
  } else {
    return <img className="__avatarimage" src={this.props.user.avatar} />;
  }
};

var avatar = createAvatar();
return <div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
  {avatar}
</div>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM