首页 > 解决方案 > 如何使重复按钮仅适用于特定的 div

问题描述

我有一个笔记应用程序,它显示带有编辑和删除选项的笔记。如何使编辑/删除按钮仅在该注释 div 上起作用?现在,每当我按下编辑/删除时,它只适用于第一个音符,而不是我单击按钮的特定音符。

显示.js:

 render(){
    const notesList = this.props.notesList;
    const displayNotes = notesList.map( (note) =>
      <div className="display">
        <p id="note">{note}</p>
        <button type="button" class="edit-button" onClick={this.props.edit}>Edit</button>
        <button type="button" class="delete-button" onClick={this.props.delete}>Delete</button>
      </div> );

    return <div>{displayNotes}</div>;
  }

应用程序.js:

handleEdit = () => {
   document.getElementById('note').contentEditable = "true";
  }

标签: javascripthtmlcssreactjs

解决方案


此代码将不起作用。在您的 handleEdit 函数中,它只需要第一个带有 id 'note' 的元素。React 不知道您要删除或编辑哪个注释。笔记存储在哪里?notesList 数组在您的应用程序中的所有位置都相同吗?然后,您可以使用例如索引来过滤掉要删除或编辑的注释。

在您的地图功能中,您可以像这样添加索引noteList.map((note, index) => {}

也许你的 handleEdit 函数会是这样的:

const handleEdit = (index) => {theNotes[index].contentEditable = "true"}

我使用了一个虚拟变量 theNotes,因为我不知道您是如何实现应用程序的状态的。


推荐阅读