繁体   English   中英

整个 div 是可点击的。 div 在角落有一个图标,我希望在单击此图标时不单击 div

[英]Entire div is clickable. The div has an icon in the corner, and I want the div to not be clicked when clicking this icon

在此处输入图片说明

上图中的所有内容都在 React-Router Link标签内。 单击任何灰色区域都会将用户带到包含有关“洋葱”的更多信息的页面。 心脏是一个字体很棒的i标签,它有一个 onClick 处理程序,可以将点击的食谱添加到用户的收藏夹中。 单击它确实成功收藏了帖子,但它也会触发底层链接,将用户带到更多详细信息页面。

如何在不单击附加到基础 div 的链接的情况下单击心脏?

注意:灰色框是 className="recipecard-content-FEED" 的元素。 其他注释在下面的代码中注释。

这个 div 的 JSX 代码:

<Link to={{pathname: `/recipe/${recipe.id}`, component: 'Feed'}}>
    <div className="recipecard-content-FEED" }> // This is the gray box

        <div className="recipe-title-FEED-container">
            <h1 className="recipe-title-FEED">{recipe.title}</h1> // This is 'onion'
            {this.renderAddOrRemoveFavorite(recipe)} // This renders the heart
        </div>

        <p className="recipe-author-FEED"></p> // This is 'bammbi'

        <h2 className="recipe-cooktime-FEED">{recipe.cooktime}</h2> // This is '20'

    </div>
</Link>

心脏:

<div className="favorite_btn" onClick={() => this.addFavorite(this.props.auth.user.id, recipe.id)}>
    <i className="far fa-heart"></i>
</div>

有两种选择可以解决这个问题。

  1. 在 heart 上添加 Click 事件,并在将其添加到收藏夹后防止默认。

  2. 使用单击事件删除链接路由器和路由。 和带 ID 的道目标。

    如果 'id; 目标元素的核心然后忽略路由否则将其路由到详细信息页面。

你可以给图标添加一个onClick函数来防止链接通过,然后指定你想要点击图标后发生什么。

const handleClick = (e) => {
  e.preventDefault();

  // handle click behavior here
}

<i className="far fa-heart" onClick={handleClick} />

一个有点混乱的解决方案:

我可以将其中的每个单独项目设为链接,而不是将整个灰色容器设为链接。 这样,心脏就会按预期工作,单击其他链接旁边的框上的任意位置仍会将您带到更多详细信息页面。

        <div className="recipecard-content-FEED" style={ this.getRecipePicture(recipe) }>

            <div className="recipe-title-FEED-container">
              <Link to={{pathname: `/recipe/${recipe.id}`, component: 'Feed'}}>
                <div className="recipe-title-FEED">
                  <h1>{recipe.title}</h1>
                </div>
              </Link>
              {this.renderAddOrRemoveFavorite(recipe)}
            </div>

            <Link to={{pathname: `/recipe/${recipe.id}`, component: 'Feed'}}>
              <p className="recipe-author-FEED">
                <Link style={{textDecoration: 'underline', color: 'rgb(230, 220, 200)'}} to={`/profile/${recipe.author}`}>
                  {recipe.username}
                </Link>
              </p>
            </Link>

            <Link to={{pathname: `/recipe/${recipe.id}`, component: 'Feed'}}>
              <h2 className="recipe-cooktime-FEED">{recipe.cooktime}</h2>
            </Link>
       </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM