如何使用ReactJS从html表中删除整行?

时间:2017-09-18 20:51:19

标签: reactjs

我想在点击按钮时从html表中删除整行(text& button)。如何使用ReactJS代替使用简单的JavaScript?

var RecordsComponent = React.createClass({
    render : function() {
        return (
            <div>
                <table>
                    <tr>
                        <td>row 1</td>
                        <td><button onClick={deleteRow}>DELETE</button></td>
                    </tr>
                    <tr>
                        <td>row 2</td>
                        <td><button onClick={deleteRow}>DELETE</button></td>
                    </tr>
                    <tr>
                        <td}>row 3</td>
                        <td><button onClick={deleteRow}>DELETE</button></td>
                    </tr>
                </table>
            </div>
        );
    },
    deleteRow : function() {
        //how to delete row using ReactJS?
    },
});

React.render(<RecordsComponent/>, document.getElementById('display'))

1 个答案:

答案 0 :(得分:0)

您应该知道如何制作反应组件。 以下是删除项目的示例之一。

class RecordsComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      rows: ['row 1', 'row 2', 'row 3'],
    };
  }

  deleteRow = (index) => {
    // make new rows. note: react state is immutable.
    const newRows = this.state.rows.slice(0, index).concat(this.state.rows.slice(index + 1));
    this.setState({
      rows: newRows,
    });
  };

  render() {
    const rows = this.state.rows.map((row, index) => (
      <tr key={row}>
        <td>{row}</td>
        <td><button onClick={() => { this.deleteRow(index); }}>DELETE</button></td>
      </tr>
    ));
    return (
      <div>
        <table>
          {rows}
        </table>
      </div>
    );
  }
}