如何在REACT js的.map()函数中仅禁用选定的按钮onClick

时间:2019-04-17 19:17:12

标签: javascript reactjs onclick setstate map-function

我在 REACT js中有购物应用程序。我使用.map()函数显示所有产品,并在每个产品的前面显示“ ADD to CART”按钮。单击 ADD到购物车 btn时,它将单击的产品ID添加到本地存储中,然后我通过检索ID在购物 购物车中显示这些选定的产品来自 localStorage 。一切都很好

现在,我想要的是单击“一次”后禁用“添加到购物车”按钮(仅适用于所选产品)。我是通过设置状态来完成此操作的,但是实际上它禁用了所有产品 前面的所有“添加到购物车”按钮,而不是仅禁用所选按钮。

我搜索了很多这个问题,而到处都只有将 setState 设置为true / false来启用/禁用按钮。我这样做了,但是没有用,因为它是针对该页面上的 ALL 产品的。请帮我该怎么办。

这是我的REACT JS代码:

export default class SpareParts extends Component
{
  constructor()
  {
      super()
      this.state = {
        spareParts: [],
        cart: [],
        inCart: false,
        disabledButton: false
      };

      this.ViewDeets = this.ViewDeets.bind(this);
      this.AddToCart = this.AddToCart.bind(this);
  }


  ViewDeets= function (part)
  {
    this.props.history.push({
                pathname: '/partdetails',
                 state: {
                    key: part
                }
            });
  }

  AddToCart(param, e)
  {
  
    var alreadyInCart = JSON.parse(localStorage.getItem("cartItem")) || [];
    alreadyInCart.push(param);
    localStorage.setItem("cartItem", JSON.stringify(alreadyInCart));

    this.setState({
      inCart: true,
      disabledButton: true
    })

  }

  
  componentDidMount()
  {
    console.log("Showing All Products to Customer");

        axios.get('http://localhost/Auth/api/customers/all_parts.php', {
        headers: {
         'Accept': 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
         }} )
       .then(response =>
       {
       this.setState({
              spareParts :response.data.records
            });
       })
         .catch(error => {
         if (error) {
           console.log("Sorry Cannot Show all products to Customer");
           console.log(error);
         }
           });
  }

render()
  {
    return (

<div id="profileDiv">

{this.state.spareParts.map(  part =>


<Col md="3" lg="3" sm="6" xs="6">
  <Card>

  <Image src={"data:image/png[jpg];base64," +  part.Image}
  id="partImg" alt="abc" style={ {width: "90%"}} />

  <h4>  {part.Name} </h4>
  <h5> Rs. {part.Price}  </h5>
  <h5> {part.Make} {part.Model} {part.Year} </h5>
  <h5> {part.CompanyName} </h5>

<button
    onClick={()=> this.ViewDeets(part) }>
    View Details
</button>

<button onClick={() => this.AddToCart(part.SparePartID)}
   
   disabled={this.state.disabledButton ? "true" : ""}>
  {!this.state.inCart ? ("Add to Cart") : "Already in Cart"}
</button>

  </Card>
</Col>

)}

</div>

);
  }
}

1 个答案:

答案 0 :(得分:1)

您一次只需要禁用一个按钮吗?如果是这样,请将您的状态更改为不是布尔值,而是一个数字,指示禁用了哪个按钮。然后在渲染中,仅当要渲染的按钮具有与该状态中找到的索引相同的索引时,才能禁用该功能。

this.state = {
   disabledButton: -1
   // ...
}

// ...

AddToCart(index, param, e) {
  //...
  this.setState({
    inCart: true,
    disabledButton: index
  })
}


// ...

{this.state.spareParts.map((part, index) => {
   // ...
  <button onClick={() => this.AddToCart(index, part.SparePartID)}
    disabled={this.state.disabledButton === index}>
    {!this.state.inCart ? ("Add to Cart") : "Already in Cart"}
  </button>
})}

如果每个按钮需要同时独立禁用,则将状态更改为与备件长度相同的布尔数组,并在render方法中让每个按钮查找是否应禁用它在那个阵列中。

this.state = {
  spareParts: [],
  disabledButtons: [],
  // ...
}

// ...

axios.get('http://localhost/Auth/api/customers/all_parts.php', {
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
    }} )
.then(response =>{
  this.setState({
    spareParts: response.data.records,
    disabledButtons: new Array(response.data.records.length).fill(false)
  });
});

// ...

AddToCart(index, param, e) {
  //...
  this.setState(oldState => {
    const newDisabledButtons = [...oldState.disabledButtons];
    newDisabledButtons[index] = true;
    return {
      inCart: true,
      disabledButtons: newDisabledButtons,
    }
  });
}

// ...

{this.state.spareParts.map((part, index) => {
   // ...
  <button onClick={() => this.AddToCart(index, part.SparePartID)}
    disabled={this.state.disabledButtons[index]>
    {!this.state.inCart ? ("Add to Cart") : "Already in Cart"}
  </button>
})}