简体   繁体   English

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

[英]How to disable only selected button onClick inside .map() function of REACT js

I have shopping Application in REACT js. 我在REACT js中有购物应用程序。 Im displaying all products using .map() function, and also showing "ADD to CART" button infront of each product. 我使用.map()函数显示所有产品,并在每个产品的前面显示“ ADD to CART”按钮。 When ADD to Cart btn is clicked, it adds the clicked product ID in local storage then I display these selected products in Shopping Cart by retrieving IDs from localStorage . 单击添加到购物车 btn时,它将单击的产品ID添加到本地存储中,然后通过从localStorage检索ID将这些所选产品显示在Shopping Cart中 It all works fine . 一切正常

Now what I wanted is to disable the "ADD to Cart" button(for selected product only) when its clicked Once. 现在,我想要的是单击“一次”后禁用“添加到购物车”按钮(仅适用于所选产品)。 I did it by setting state but it actually Disables ALL "ADD to Cart" Buttons infront of all PRODUCTS instead of disabling only selected button. 我通过设置状态来做到这一点, 但实际上它禁用了所有产品前面的所有“添加到购物车”按钮而不是仅禁用选定的按钮。

I searched this issue alot, and the soltion I got everywhere is just to setState to true/false to enable/disable button. 我搜索了很多这个问题,而到处都只有将setState设置为true / false才能启用/禁用按钮。 I did it but no use because its doing it for ALL products on that Page. 我这样做了,但是没有用,因为它对该页面上的所有产品都这样做。 Please help me what to do. 请帮我该怎么办。

Here is my REACT JS code: 这是我的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> ); } } 

Do you only need to disable one button at a time? 您是否只需要一次禁用一个按钮? If so, change your state to be not a boolean but a number indicating which button is disabled. 如果是这样,请将您的状态更改为不是布尔值,而是一个数字,指示禁用了哪个按钮。 Then in render, only disable if the button you're rendering has the same index as found in the state. 然后在渲染中,仅当要渲染的按钮与状态中找到的索引相同时才禁用。

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>
})}

If instead each button needs to be independently disableable at the same time, change your state to be an array of booleans with the same length as the spare parts, and in the render method have each button look up whether it should be disabled in that array. 如果相反,每个按钮需要同时被独立禁用,则将状态更改为与备件长度相同的布尔数组,并在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>
})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM