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

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

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

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

2条回答
  •  鱼传尺愫
    2020-12-15 15:31

    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 state because it can cause easily bugs or an unexpected behavior.

    Look closely how the handling functions are working.

    Here you 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 (
          
    {this.state.rows.map((item, idx) => ( ))}
    # Name Mobile
    {idx}
    ); } } render(, 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 - javascript to move forward because it would helpful to achieve things like this faster, right now you need to understand the basics pretty good.

提交回复
热议问题