如何只禁用REACT js里面的.Click()函数的onClick按钮

问题描述 投票:0回答:1

我在REACT js购物申请。我使用.map()函数显示所有产品,并在每个产品前面显示“ADD to CART”按钮。单击ADD to Cart btn时,它会将单击的产品ID添加到本地存储中,然后通过从localStorage检索ID,在Shopping Cart中显示这些选定的产品。一切正常。

现在我想要的是当它点击一次时禁用“添加到购物车”按钮(仅适用于所选产品)。我是通过设置状态来实现的,但它实际上禁用所有“ADD to Cart”按钮,而不是仅禁用所选按钮。

我搜索了这个问题很多,而我到处获得的解决方案只是将setState设置为true / false来启用/禁用按钮。我做了但没有用,因为它为该页面上的所有产品做了。请帮帮我怎么做。

这是我的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>

);
  }
}
javascript reactjs onclick setstate map-function
1个回答
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>
})}

© www.soinside.com 2019 - 2024. All rights reserved.