如何在React.js中动态添加和删除表行

时间:2018-03-08 10:40:55

标签: javascript reactjs

3 个答案:

答案 0 :(得分:5)

你可以通过玩反应​​状态来达到目的。在您的情况下,您正在使用嵌套对象,因此在更新它们时需要小心。

改变你的state并不是一个好主意,因为它可能会导致错误或意外行为。

仔细查看handling函数的工作原理。

Here你有一个现场演示。

class App extends React.Component {
  state = {
    rows: []
  };
  handleChange = idx => e => {
    const { name, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [name]: value
    };
    this.setState({
      rows
    });
  };
  handleAddRow = () => {
    const item = {
      name: "",
      mobile: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
  render() {
    return (
      <div>
        <div className="container">
          <div className="row clearfix">
            <div className="col-md-12 column">
              <table
                className="table table-bordered table-hover"
                id="tab_logic"
              >
                <thead>
                  <tr>
                    <th className="text-center"> # </th>
                    <th className="text-center"> Name </th>
                    <th className="text-center"> Mobile </th>
                  </tr>
                </thead>
                <tbody>
                  {this.state.rows.map((item, idx) => (
                    <tr id="addr0" key={idx}>
                      <td>{idx}</td>
                      <td>
                        <input
                          type="text"
                          name="name"
                          value={this.state.rows[idx].name}
                          onChange={this.handleChange(idx)}
                          className="form-control"
                        />
                      </td>
                      <td>
                        <input
                          type="text"
                          name="mobile"
                          value={this.state.rows[idx].mobile}
                          onChange={this.handleChange(idx)}
                          className="form-control"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <button
                onClick={this.handleAddRow}
                className="btn btn-default pull-left"
              >
                Add Row
              </button>
              <button
                onClick={this.handleRemoveRow}
                className="pull-right btn btn-default"
              >
                Delete Row
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
  PD:如果我可以给你一个推荐,我会说你需要更多地研究 react - javascript 来继续前进,因为它有助于更​​快地实现这样的事情,现在你需要了解相当不错的基础知识。

答案 1 :(得分:1)

如果要动态添加/删除行,可以使用状态,或者 如果你在哪里使用Redux,你可以在商店玩。

这是一个使用组件本地状态来添加和删除行的简单示例:

https://codesandbox.io/s/k302jwn44r

编辑:修正变异状态

import React from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "left"
};

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rows: []
    };
  }

  handleAddRow = () => {
    this.setState((prevState, props) => {
      const row = {content: "hello this is a new row!" };
      return { rows: [...prevState.rows, row] };
    });
  };

  handleRemoveRow = () => {
    this.setState((prevState, props) => {
      return { rows: prevState.rows.slice(1) };
    });
  };

  render() {
    console.log(this.state);
    return (
      <div style={styles}>
        <table>
          <tbody>
            {this.state.rows.map(row => (
              <tr>
                <td>{row.content}</td>
              </tr>
            ))}
            <tr>
              <td className="" onClick={this.handleAddRow}>
                (+)
              </td>
              {Boolean(this.state.rows.length) && (
                <td onClick={this.handleRemoveRow}>(-)</td>
              )}
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

答案 2 :(得分:0)

感谢楼上的回答。 关于处理“handleChange”的一点评论。 我们是否需要更改以下内容

const rowInfo = rows[idx];
rowInfo[name] = value;

到以下将数据保存到行中:

{{1}}

相关问题