删除后react动态行输入值保留

IT技术 javascript reactjs ecmascript-6
2021-05-02 15:24:27

我有以下代码的问题

export class MultipleInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rowCount: 1
    };
  }
  addRow = () => this.setState({ rowCount: this.state.rowCount + 1 });
  deleteRow = () => this.setState({ rowCount: this.state.rowCount - 1 });
  renderRow = i => {
    const { type, value } = this.props;
    const { rowCount } = this.state;
    return (
      <div>
        <input type={type} value={value} />
        <button onClick={this.addRow}>add</button>
        {i > 0 && <button onClick={this.deleteRow}>delete</button>}
      </div>
    );
  };
  render() {
    const { rowCount } = this.state;
    return <div>{times(rowCount, this.renderRow)}
      <br /><br />
      problems
      <p>when there is more input, says i enter something in the input, fill something, then click remove, the value is filled in other value</p>
    </div>
  }
}

要重现单击添加,请在第二个输入中填写一些值,然后单击第二行的删除,输入的值在那里。

演示https://codesandbox.io/s/4x0x17zykx

2个回答
import React from "react";
import ReactDOM from "react-dom";

export class MultipleInput extends React.Component {
  state = {
    rowCount: 1
  };
  addRow = () => {
    this.setState(({ rowCount }) => ({
      rowCount: rowCount + 1,
    }));
  };
  deleteRow = () => {
    this.setState(({ rowCount }) => ({
      rowCount: rowCount - 1,
    }));
  };

  renderRow = i => {
    const { type, value } = this.props;
    const { rowCount } = this.state;
    return (
      <div>
        <input type={type} value={value} />
        <button onClick={this.addRow}>add</button>
        {rowCount > 1 && <button onClick={this.deleteRow}>delete</button>}
      </div>
    );
 };
 render() {
    const { rowCount } = this.state;
    return Array(rowCount).fill(1).map(i => this.renderRow(i));
 }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MultipleInput />, rootElement);

注意事项

您需要像上面一样增加/减少您的状态,添加前一个状态以更新当前状态;

在渲染中,我创建了一个rowCount没有的新数组元素,以映射renderRow方法。你不需要lodash这个。

现在,当此组件中有多个输入字段时,将显示删除按钮。IE,{rowCount > 1 && <button onClick={this.deleteRow}>delete</button>}

单击删除时,您将数组大小减少 1,无论您单击哪个删除按钮,它都将始终删除最后一行,因为您删除了数组的最后一个元素。您需要为每一行提供一个唯一的 id,并从数组中删除具有该 id 的元素,而不是最后一个元素。按以下方式使用地图功能

Array.map((i,idx)=>{this.renderRow(i, idx)})

现在,每次调用 renderRow 函数时,都会有一个唯一的递增数字传递给它,因此该数字可以用作 id。将此 id 传递给 renderRow 函数中的输入字段

<input type={type} value={value} id={idx} />

您可以维护这些 id 的数组而不是行数,因此如果您有 1 行,那么您的数组中的所有内容都是第一个 id,即 [0],对于 2 行 [0,1],依此类推。

现在,当您单击删除时,传递 id,然后从 DOM 中删除该特定 id

deleteRow= (idx) => {
     var elem = document.getElementById(idx);
     if (elem.parentNode) {
         elem.parentNode.removeChild(elem);
     }
 this.setState({//Here you can reduce the row count
                        });
        }