Getting div's attribute value in the different function (REACT)

问题: So basically, I have just started learning React and I wanted to create a simple add, which works as a shopping car. I am just wondering how to pass the price of an item to...

问题:

So basically, I have just started learning React and I wanted to create a simple add, which works as a shopping car. I am just wondering how to pass the price of an item to the function. I have done something like that below but it doesn't work and probably is not the best idea.

 <div className="item" onClick={this.addItem} itemPrice={12}><p class="itemDesc">Pizza</p></div>

   addItem() {
     let myItems = this.state.itemsOrdered;
     let myPrice = this.state.price;

     this.setState({
       itemsOrdered: myItems + 1,
       price: myPrice + this.itemPrice
     });
   }

I expect state price to increase by the value of clicked item


回答1:

You first need to fix the following errors:

  1. Change the camel-case itemPrice to lowercase like this itemprice since React doesn't allow camel-case format for custom attributes.

  2. class is a reserved keyword in JavaScript. Replace: <p class="itemDesc"> with <p className="itemDesc">.


So in order to access the clicked element's itemprice value and add it to your state property, you need to:

First, pass the clicked event object as a parameter to addItem() like this:

addItem(e) {

}

Second, assign the div you just clicked to a variable say, clickObj like this:

addItem(e) {
    let clickObj = e.currentTarget;
}

Third, retrieve the value of the itemprice attribute using the getAttribute method, parsed it to an integer and then assign it to another variable, say newPrice.

addItem(e) {
    let clickObj = e.currentTarget;
    let newPrice = parseInt(clickObj.getAttribute('itemprice'));
}

Fourth, Add the values of this.state.price and newPrice and then assign it to this.state.price like this:

addItem(e) {
    let clickObj = e.currentTarget;
    let newPrice = parseInt(clickObj.getAttribute('itemprice'));
    this.setState({
        price: this.state.price + newPrice
    });
}

Check the codepen below to see how I use the above approach to increment a state property's value on click:

CodePen: https://codepen.io/andrewl64/pen/wRdvqP

  • 发表于 2018-12-27 11:14
  • 阅读 ( 163 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除