首页 > 解决方案 > DOM 元素的动态唯一值

问题描述

我想知道我的解决方案是否是传统的和/或是否有更好、更常见的方法在这种情况下使用 React:

我有评论区。我从服务器检索评论列表作为我的功能组件的道具。在 JSX 中,我映射每条评论,并为每条评论返回一个 TextArea 来显示评论。其中一项功能是,如果您创建了评论,则会出现一个编辑按钮,从而使 textarea 可编辑。

这意味着我需要每个文本区域的唯一标识符,因为一旦用户编辑评论的内容并单击保存按钮,我需要使用数据库中评论的正确 _id 以及更新的内容发布到我的服务器。到目前为止,我最惯用的解决方案是使用 refs,代码如下:

  1. 我创建了一个包含数组的 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)}

  2. 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)}...

  3. 最后,一旦单击保存按钮,其 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)} ...

这可行,但这是否太复杂了,有没有更好和通用的解决方案?我尝试过/考虑过的其他解决方案:

提前致谢!

标签: reactjs

解决方案


你不需要使用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的组件属性(标题取决于模式)editableedit/save


推荐阅读