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

前端 未结 2 1687
甜味超标
甜味超标 2020-12-15 14:51
 my attempt fiddle here ..........

https://jsfiddle.net/techboy0007/j1eas924/

https://i.stack.imgur.com/KXFot.png

2条回答
  •  Happy的楠姐
    2020-12-15 15:44

    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.

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

    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 (
          
    {this.state.rows.map(row => ( ))} {Boolean(this.state.rows.length) && ( )}
    {row.content}
    (+) (-)
    ); } } render(, document.getElementById("root"));

提交回复
热议问题