【问题标题】:How to delete a specific textfield inside a table onclick of a button using reactjs & material ui如何使用reactjs和material ui删除表格内的特定文本字段
【发布时间】:2021-08-11 06:02:37
【问题描述】:

每当单击特定行删除按钮时,我想删除表格内特定行上的文本字段,目前我能够添加文本字段 onclick 的添加按钮,并且我能够删除 textField onclick 的删除按钮但是每当单击删除按钮时,所有文本字段都会被删除,而不是特定的文本字段此外,添加图标需要位于最后一个文本字段旁边,但目前我只能在第一个文本字段上实现它。请有人在这里帮助我。到目前为止我所取得的成就的形象。

如您所见,我正在尝试删除第一行的文本字段,但它会自动删除表格每一行中的文本字段。

工作代码框:https://codesandbox.io/s/heuristic-fermat-63ixw?file=/src/App.js

谁能帮帮我

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6 material-ui


    【解决方案1】:

    问题

    您正在添加多个具有相同 rowId 的自定义行,因此当您过滤它们时,您删除的内容超出了您的预期。

    您还错误地将newRow.rowIdthis.state.customRow.rowId 进行了比较,因为它是一个数组,因此当然是未定义的,并更新您的状态以将customRow 嵌套到另一个数组中。

    handlingDeleteRow = (index, newRow) => {
      let newdel = this.state.customRow.filter(
        (newRow) => newRow.rowId !== this.state.customRow.rowId // <-- incorrect comparison
      );
      this.setState({
        customRow: [newdel] // <-- nest array in array
      });
      console.log(this.state.customRow);
    };
    

    解决方案

    我建议为您添加的自定义行添加一个 guid 并在其上进行匹配。

    import { v4 as uuidV4 } from 'uuid';
    
    ...
    
    addCustomFile = (index) => {
      this.setState({
        resError: null,
        customRow: [
          ...this.state.customRow,
          { rowId: index, fileData: false, fileName: false, guid: uuidV4() }
        ]
      });
    };
    

    删除时使用新的guid 属性。

    handlingDeleteRow = (index, newRow) => {
      let newdel = this.state.customRow.filter(
        (row) => row.guid !== newRow.guid
      );
      this.setState({
        customRow: newdel
      });
    };
    

    演示

    【讨论】:

      【解决方案2】:

      我阅读了您的代码,它运行良好。

      您要添加的一件事是单行中文本输入的索引。

      问题

      目前,如果用户按三下 + 按钮,addCustomFile 将向state.customRow 添加三个元素。但是,这三个元素是相同的,没有什么可区分的。

      这就是为什么filter 函数(在按下 X 按钮时执行)将删除state.customRow 中的所有元素 属于同一行

      解决方案

      我建议你给state.customRow的元素添加一个新属性来区分同一行的添加输入。例如,它可以是insideRowIndex,并且每个添加的输入都可以有递增的整数(0,1,2,3,4 ...)。

      在过滤器函数中检查 insideRowIndex 将让您只删除您打算删除的输入,而不是属于同一函数的所有其他输入。

      【讨论】:

        猜你喜欢
        • 2021-01-21
        • 2016-06-17
        • 2021-08-19
        • 1970-01-01
        • 2011-11-30
        • 2021-10-29
        • 1970-01-01
        • 2020-09-14
        • 2021-11-27
        相关资源
        最近更新 更多