首页 > 解决方案 > 如何在反应中使用 onClick 增加值

问题描述

按下 onClick 触发器时我有一个按钮,该按钮LikeComment使用当前评论 ID 和发布评论的用户将类似内容发布到数据库。

    <button className="btn" onClick={LikeComment(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{comment_likes.length}</p>
      </div>
    </button>

comment_likes.length按下按钮时增加的最佳方法是什么。现在我的问题是该值仅在页面刷新时更新。

我试图这样做,但它没有按预期工作

<p>{comment_likes.length && LikeComment ? (comment_likes.length+1) : (comment_likes.length)}</p>

我想通过检测何时按下 LikeComment 以将原始值增加 1 来实现这一点。

任何解决此问题的提示将不胜感激..

标签: javascriptreactjsconditional-operator

解决方案


首先,您需要将当前的类似数量存储在组件的本地状态中。这样你就可以只显示当前的喜欢数量,如果你改变buttonLikes数量,react 会自动更新显示。

const [buttonLikes, setButtonLikes] = useState(comment_likes)

然后你需要一个事件处理程序,它将增加类似的数量并将你的更改发布到数据库


    const handleClickLikeButton = (comment_id, user_id) => {
        setButtonLikes((prevValue) => prevValue + 1)
        LikeComment(comment_id, user_id)
    }

现在您的显示逻辑将如下所示

   <button className="btn" onClick={handleButtonLike(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{buttonLikes}</p>
      </div>
    </button>

推荐阅读