如何使Reactjs CRUD表可编辑?

时间:2017-10-03 03:19:47

标签: reactjs

我正在为工作中的项目制作这个动态/ CRUD表。我被困在项目的这一部分,如果我按下编辑按钮,我希望我桌子上的数据变得可编辑或在我的数据周围显示一个输入文本字段框。

我已经设置了编辑按钮的骨架,但功能不起作用。 handleRowEdit(product){行是其中所需内容的一部分。

我知道要添加和删除你必须使用拼接和推送方法。

class Books extends React.Component {

 constructor(props) {
    super(props);

this.state = {};
this.state.filterText = "";
this.state.products =  [ 
    {
    name: "Jim Hoskins",
    author: "Arthur Conan Doyle",
    genre: "Murder & Mystery",
    dateAdded: "1/18/2015 2:24:12 PM",
    OutofPrint: "False",
    id: 1,
    },

    {
    name: "The Scowrers",
    author: "Arthur Conan Doyle",
    genre: "Murder & Mystery",
    dateAdded: "1/1/2016 4:55:54 AM",
    OutofPrint: "True",
    id: 2,
    },
    ];


this.handleAddEvent = this.handleAddEvent.bind(this);
this.handleRowDel = this.handleRowDel.bind(this);
this.handleRowEdit = this.handleRowEdit.bind(this);
   }


handleRowDel(product) {
      var index = this.state.products.indexOf(product);
      this.state.products.splice(index, 1);
        this.setState(this.state.products);
       };

 handleRowEdit(product){
     this.setState(this.state.products);
        }

  handleAddEvent(e) {
       var id = (Math.floor(Math.random() * 999999)).toString(36);
     var product = {
        id: id,
        name: "",
           author: "",
        dateAdded: "",
        OutofPrint: "",
         }
        this.state.products.push(product);
       this.setState(this.state.products);
      }    

这不是所有的代码,但就像我说的,我已经设置了编辑按钮,但我没有它背后的功能。

1 个答案:

答案 0 :(得分:0)

在构造函数中,您可以按如下方式设置状态:

this.state = {
    filterText : "",
    products :  [ 
    {
    name: "Jim Hoskins",
    author: "Arthur Conan Doyle",
    genre: "Murder & Mystery",
    dateAdded: "1/18/2015 2:24:12 PM",
    OutofPrint: "False",
    id: 1,
    },    
    {
    name: "The Scowrers",
    author: "Arthur Conan Doyle",
    genre: "Murder & Mystery",
    dateAdded: "1/1/2016 4:55:54 AM",
    OutofPrint: "True",
    id: 2,
    },
    ]
    };

在事件处理程序中,当您修改状态时,应该以不可变的方式执行此操作。

handleRowDel(product) {
  //quick deep copy. use Immutable.js for better immutable data structures
  let localProducts = JSON.parse(JSON.stringify(this.state.products));
  var index = localProducts.indexOf(product);
  localProducts.splice(index, 1);
  this.setState(localProducts);
}

您可以以类似的方式更改添加处理程序。

对于编辑处理程序

handleRowEdit(product) {
  //quick deep copy. use Immutable.js for better immutable data structures
  let localProducts = JSON.parse(JSON.stringify(this.state.products));
  let index =localProducts.findIndex(p=>p.id===product.id);
  localProducts[index] = product;
  this.setState(localProducts);
}

希望这有帮助!