【发布时间】:2020-10-03 20:45:21
【问题描述】:
我想将项目添加到总计中(添加价格)。因此,当我单击(添加到购物车)时,它只会添加商品数量,但我想准确添加(总和)价格。
class BookStore extends Component {
constructor(props){
super(props);
this.state = {
total: 0,
active: false,
}
this.clicker = this.clicker.bind(this);
}
clicker() {
let active = !this.state.active;
this.setState({
active: active,
total: this.state.total + 1
})
};
render() {
console.log(this.props.books);
return (
<div className='container'>
<div className='row'>
<span className='mt-4'>Total: {this.state.total}</span>
{this.props.books.map((book, i)=> {
return (
<>
<div className='col-12 card book-card' key={i}>
<div className='row'>
<div className='col-8'>
<h5>{book.name}</h5>
<h6>$ {book.price}</h6>
</div>
<div className='col-4'>
<button onClick={this.clicker} className=' btn btn-success' style={{width: '50%', }}>add to cart</button>
</div>
</div>
</div>
</>
)
})}
</div>
</div>
)
}
}
那么我如何将该价格添加到与相应书籍相关的总计中。 (我的意思是,当我点击按钮时,我需要在 {this state total} 字段中显示总计
【问题讨论】:
-
使用 Array.reduce 函数计算总数 -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript reactjs components