React 所有评论选项一键出现

React all comment options appear by one click

我有这段代码,我在其中循环 post 数组以提取 comments



  const [commentOptions, setCommentOptions] = useState(false);

   return(
...

        {post.comments.map((comment) => (
          <div className="comments" key={comment._id}>
            <div className="commentUserImageAndUsername">
              <img
                className="commentUserImg"
                src={
                  comment.userId === users._id
                    ? users.profileImg || `${PF}/profile.jpg`
                    : null
                }
                alt="comment user "
              />
              {comment.userId === users._id ? users.firstname : null}
            </div>
            <div className="commentBody">{comment.body}</div>
            {user._id === comment.userId ? (
              <div
                className="commentOptionsMark"
                onClick={() => setCommentOptions(!commentOptions)}
              > - </div>
            ) : null}
            {commentOptions ? (
              <div className="commentOptions">
                <div className="deleteComment">Delete</div>
                <div className="editComment">Edit</div>
              </div>
            ) : null}
          </div>
        ))}
...
)

对于每个 comment 我有 hyphen 标记 -,如果我点击它,它会将 commentOptions 状态设置为真,因此 commentOptions div 将出现,其中包含 2 个选项 delete commentedit comment,问题是如果我单击 hyphen mark 进行一条评论, commentOptions div 将出现每个评论,如果有 5 条评论,每条评论都有自己的选项,我可以通过单击控制每条评论 commentOptions div 的外观,这不是我想要的,我想显示一个 [=28] =] 对于点击时的每条评论 hyphen -,不是一次全部评论,就像每条评论自己一样,如何解决?

存储被点击的评论id用于控制:

const [shownCommentId, setShownCommentId] = useState('');


{user._id === comment.userId ? (
      <div
         className="commentOptionsMark"
         onClick={() => setShownCommentId(comment._id)}
      > - </div>
) : null}

然后在你的地图中控制id:

{shownCommentId === comment._id ? (
      <div className="commentOptions">
          <div className="deleteComment">Delete</div>
          <div className="editComment">Edit</div>
      </div>
 ) : null}