javascript - 如何在反应中使用 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 来实现这一点。
任何解决此问题的提示将不胜感激..
解决方案
首先,您需要将当前的类似数量存储在组件的本地状态中。这样你就可以只显示当前的喜欢数量,如果你改变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>
推荐阅读
- ssis - SSDT 2017 安装失败 无法打开配置注册表项
- node.js - Alexa API 技能 - nodejs 获取请求未执行
- bots - 我的 GupShup 机器人迷路了?
- ios - ios - 如何将 mtl 纹理文件应用于 OBJ
- typescript - 如何注释一个接受类并返回具有静态成员的工厂的函数?
- python - 在python中比较列表和文件以进行匹配
- javascript - Javascript 将响应对象解析为对象数组
- jquery - 如果页面上存在动态创建的跨度类,则显示 div
- javascript - 如何更新 Vue.JS 中的插槽
- c++ - 为什么注入的类名有时不被视为类模板中的模板名?