reactjs - DOM 元素的动态唯一值
问题描述
我想知道我的解决方案是否是传统的和/或是否有更好、更常见的方法在这种情况下使用 React:
我有评论区。我从服务器检索评论列表作为我的功能组件的道具。在 JSX 中,我映射每条评论,并为每条评论返回一个 TextArea 来显示评论。其中一项功能是,如果您创建了评论,则会出现一个编辑按钮,从而使 textarea 可编辑。
这意味着我需要每个文本区域的唯一标识符,因为一旦用户编辑评论的内容并单击保存按钮,我需要使用数据库中评论的正确 _id 以及更新的内容发布到我的服务器。到目前为止,我最惯用的解决方案是使用 refs,代码如下:
我创建了一个包含数组的 ref,一个用于传递将 comment._id 映射到元素的对象的函数,并在调用该函数时将其添加到 commentRefs 数组中。添加到 ref 数组的函数是 textarea 的 ref 属性值:
const addCommentRef = _id => el => { if(el && !commentRefs.current.includes(el) && el) { const commentRef = { _id, el, content: '', } commentRefs.current.push(commentRef); }
}
<textarea ref={addCommentRef(comment._id)}
On the textarea onChange, I call a function called editCommentRef, which maps through the commentRefs, compares the ID's passed as param with each _id value in the array and if found, updates the content to what has been typed into the textarea:
const editCommentViaRef = _id => event => { for(let i = 0; i < commentRefs.current.length; i++) { const commentRef = commentRefs.current[i]; if(_id == commentRef._id) { commentRefs.current[i] = { ...commentRefs.current[i], content: event.target.value } } }
}
<textarea onChange= {editCommentRefs(comment._id)}...
最后,一旦单击保存按钮,其 onClick 处理程序将调用名为“saveCommentEdit”的第三个函数,并在其中传递注释的 _id。我们再次遍历 commentRefs 数组并找到与保存对象的 _id 匹配的 _id 参数。一旦找到,我就有了我需要发布到服务器/数据库并更新评论的内容:
const saveCommentEdit = _id => { commentRefs.current.forEach((comment) => { if(_id == comment._id) { console.log('找到要保存到数据库的评论', comment._id + ' 保存内容 - \n' + comment.content); } }); }
<button onSubmit={saveCommentEdit(comment._id)} ...
这可行,但这是否太复杂了,有没有更好和通用的解决方案?我尝试过/考虑过的其他解决方案:
状态 - 我想我会遇到与状态相同的问题,因为需要在代码中引用状态名称,所以我需要为每个状态使用不同的变量名称。此外,states 将要求整个组件在输入 textarea 的每个字符时重新渲染,这似乎比 refs 更昂贵。
文档选择器 - 最简单的解决方案是调用一个函数,该函数使用“findElementById”等以元素的 DOM 为目标。在这种情况下,我通过使每个 textarea 的 ID 包含 comment._id 来提供唯一标识符。这里明显的问题是不鼓励直接在 React 应用程序中定位 DOM,并且从根本上与 React 框架相矛盾。
提前致谢!
解决方案
你不需要使用Ref
- 它是为了别的东西(与 通信DOM
),你的任务是不同的。您可以在每个组件中存储编辑状态并record id
从数据库中获取。您可以存储author's id
以确切知道谁可以编辑。在服务器上,更新记录,前提是 id 和 author 相同。此外,您不需要执行任何循环,注释组件可以根据OOP
.
例如comments
,您的数据库中可能有一个表:
ID | post_id | author_id | 评论 |
---|---|---|---|
1 | 1000 | 用户 100 | 凉爽的 |
2 | 1001 | 用户42 | 你好 |
然后获取所有评论,post_id
如果当前 user_id 相等,您可以将其传递给显示按钮author_id
的组件属性(标题取决于模式)editable
edit/save
推荐阅读
- java - 实体管理器 - 创建查询 - 嵌套选择
- android - 将文件保存到 /storage/emulated/0/Download/ 而不是 Download 文件夹
- reactjs - 将当前路由与反应路由器匹配
- php - 如何根据条件显示消息 - 使用 laravel
- javafx - JavaFX| TableView 未填充某些字段
- javascript - 为什么这个 JS 函数在加载时不起作用?
- vb.net - 从列表框中删除特定项目 - vb.net
- amazon-web-services - 用 DynamoDB 中的新项目替换旧项目
- loops - 如何在c#中重复一个动作来修复跳跃机制
- android - 我绝对必须在我的存储中恢复文本消息