React JS类组件如何绑定独立事件实现不同按钮单独计数
问题原因
你当前的实现只在组件内维护了单个全局的cnt状态,4组商品的计数展示全部读取的是这同一个状态值,任意按钮触发修改也只会修改这同一个状态,所以所有计数会同步变更。另外你原代码中的增减方法命名和逻辑相反:命名为handleDecrement的方法实际执行了加1操作,命名为handleIncrement的方法实际执行了减1操作。
修复方案
使用数组存储多组计数的思路是正确的,只需要将单值状态改为数组,同时给增减方法增加索引参数区分操作的对应商品即可,修改后代码如下:
import React from 'react'; class Counter extends React.Component { constructor() { super(); // 数组存储4个商品各自的计数,初始值均为0 this.state = { cntList: [0, 0, 0, 0] }; } // 接收商品索引参数,执行对应位置计数加1操作 handleIncrement = (index) => { const newCntList = [...this.state.cntList]; newCntList[index] += 1; this.setState({ cntList: newCntList }); } // 接收商品索引参数,执行对应位置计数减1操作,额外增加判断避免计数为负 handleDecrement = (index) => { const newCntList = [...this.state.cntList]; if(newCntList[index] > 0) { newCntList[index] -= 1; } this.setState({ cntList: newCntList }); } render() { return ( <> <div className = "btn"></div> <header> <h1>Tarantino Shop</h1> </header> <div> <img src= "images/walltara.png" alt="cart" width = "80%"/> </div> <div className="divprimario"> <div className="items"> <img src= "images/tara1.jpg" alt="cart" /> <div className = "titles"> T-Shirt Pulp Fiction</div> <div> <button onClick={() => this.handleIncrement(0)}>+</button> <p>{this.state.cntList[0]} </p> <button onClick={() => this.handleDecrement(0)}>-</button> </div> </div> <div className="items"> <img src= "images/tara2.jpg" alt="cart" /> <div className = "titles">T-Shirt Tarantino </div> <div> <button onClick={() => this.handleIncrement(1)}>+</button> <p>{this.state.cntList[1]} </p> <button onClick={() => this.handleDecrement(1)}>-</button> </div> </div> <div className="items"> <img src= "images/tara3.jpg" alt="cart" /> <div className = "titles">T-Shirt Le Iene</div> <div> <button onClick={() => this.handleIncrement(2)}>+</button> <p>{this.state.cntList[2]} </p> <button onClick={() => this.handleDecrement(2)}>-</button> </div> </div> <div className="items"> <img src= "images/tara4.jpg" alt="cart" /> <div className = "titles">T-Shirt Random</div> <div> <button onClick={() => this.handleIncrement(3)}>+</button> <p>{this.state.cntList[3]} </p> <button onClick={() => this.handleDecrement(3)}>-</button> </div> </div> </div> </> ); } } export default Counter;
内容的提问来源于stack exchange,提问作者S F
相关产品推荐
相关产品推荐

