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

Yel*_*ion 1 javascript onclick setstate reactjs map-function

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

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

我搜索了很多这个问题,我得到的解决方案就是将State 设置为 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>

);
  }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 5

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

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>
})}
Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)