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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49171107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:27:44  来源:igfitidea点击:

How to add and remove table rows Dynamically in React.js

javascriptreactjs

回答by Arnold Gandarillas

You can achieve that by playing with react state. In your case you are using nested objects so you need to be carefully when you update them.

你可以通过玩反应​​状态来实现这一点。在您的情况下,您使用的是嵌套对象,因此在更新它们时需要小心。

It's not a good idea to mutate your statebecause it can cause easily bugs or an unexpected behavior.

改变你的不是一个好主意,state因为它很容易导致错误或意外行为。

Look closely how the handlingfunctions are working.

仔细观察这些handling函数是如何工作的。

Hereyou have a live demo.

这里有一个现场演示。

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: If I can give you a recommendation I'd say that you need to study a little bit more about react - javascriptto move forward because it would helpful to achieve things like this faster, right now you need to understand the basics pretty good.

PD:如果我可以给你一个建议,我会说你需要多学习一点关于react - javascript 的知识才能继续前进,因为它有助于更​​快地实现这样的事情,现在你需要很好地理解基础知识.

回答by Ignacio

If you want to add/remove rows dynamically you can play with the state, or if you where using Redux you can play with the store.

如果您想动态添加/删除行,您可以使用 state,或者如果您使用 Redux,您可以使用 store。

Here's a simple example using a components local state to add and remove rows:

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

https://codesandbox.io/s/k302jwn44r

https://codesandbox.io/s/k302jwn44r

EDIT: fixed mutating state

编辑:固定变异状态

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"));