React JS. NavLink activeClassName ICON, IMAGE

huangapple go评论92阅读模式
英文:

React JS. NavLink activeClassName ICON, IMAGE

问题

当活动链接为/shopping-cart时,我想要将cartIcon更改为另一张图片,我应该如何做?

英文:

I have this

 <div className="menu-item G-flex G-align-center">
     <img src={cartIcon} alt="Shopping cart" />
        <NavLink
            onClick={this.closeBar}
            to="/cart"
            activeClassName="active-page"
        >
           Shopping Cart
       </NavLink>
  </div>

So when active link is /shopping-cart I want to change cartIcon to another image, how I can ?

答案1

得分: 0

如果你指的是活动链接是URL位置,也许可以尝试这个快速修复:

<div className="menu-item G-flex G-align-center">
  <img src={window.location.href.split('/').reverse()[0] === 'shopping-cart' ? otherIcon : cartIcon} alt="购物车" />
  <NavLink
    onClick={this.closeBar}
    to="/cart"
    activeClassName="active-page"
  >
    购物车
  </NavLink>
</div>

其中,如果用户导航到 www.url.com/shooping-cart,将显示otherIcon。但你需要注意一些边缘情况,例如 www.url.com/shooping-cart/(注意末尾多余的斜杠/),将默认使用cartIcon

英文:

If by active link you mean url location, maybe try this quick fix:

 &lt;div className=&quot;menu-item G-flex G-align-center&quot;&gt;
 &lt;img src={window.location.href.split(&#39;/&#39;).reverse()[0] === &#39;shopping-cart&#39; ? otherIcon : cartIcon} alt=&quot;Shopping cart&quot; /&gt;
    &lt;NavLink
        onClick={this.closeBar}
        to=&quot;/cart&quot;
        activeClassName=&quot;active-page&quot;
    &gt;
       Shopping Cart
   &lt;/NavLink&gt;

</div>

where otherIcon is shown if user navigated to www.url.com/shooping-cart. You should be careful for some edge cases like www.url.com/shooping-cart/ (notice the extra '/' at the end), which will default to cartIcon.

huangapple
  • 本文由 发表于 2020年1月6日 20:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定