【问题标题】:How to make duplicate button only work on specific div如何使重复按钮仅适用于特定的 div
【发布时间】:2020-08-22 09:07:21
【问题描述】:

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

Display.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>;
  }

App.js:

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

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

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

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

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

    const handleEdit = (index) =&gt; {theNotes[index].contentEditable = "true"}

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

    【讨论】:

      【解决方案2】:

      您需要使用一些唯一标识给定注释的标记,例如id。然后将 id 传递给 edit/delete 函数:

      onClick={() => this.props.edit(note.id)} contentEditable={note.contentEditable}
      
      // ...
      
      this.handleEdit = (id) => {
         const idx = notesList.findIndex(note => note.id === id);
         notesList[idx] = {...notesList[idx], contentEditable: true};
         this.setState({notesList: [...notesList]});
      };
      

      【讨论】:

        【解决方案3】:

        使用动态 ID,例如 ID = "note:' + ID。 然后,通过将 ID 传递给函数参数,使用该特定 ID 操作元素。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-04-12
          • 2012-01-19
          • 1970-01-01
          • 1970-01-01
          • 2015-12-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多