React实现简易购物车项目(删除,数量加减,总价等) |
您所在的位置:网站首页 › 淘宝购物车图标数字怎么消除不了 › React实现简易购物车项目(删除,数量加减,总价等) |
才学react不久,来分享一个简易的demo,并且当购物车为空的时候展示购物车为空 先定义一个价格格式化的函数,把价格转成:¥+并且保留两位小数 function formatPrice(price){ if(typeof price !=="number"){ price = Number("aaa") || 0 } return "¥"+ price.toFixed(2) }再定义一个类组件,state里面这样的数据 class Movie extends React.Component{ constructor(){ super() this.state={ books:[ {id:1,name:"《算法导论》",datas:'2006-9',price:25,numbers:1}, {id:2,name:"《编程艺术》",datas:'2006-9',price:45,numbers:1}, {id:3,name:"《代码大全》",datas:'2006-9',price:15,numbers:1}, {id:4,name:"《天演论》",datas:'2006-9',price:115,numbers:1}, ], } }增加,减少功能 this.changeBookCount(index,-1)} disabled={item.numbers ==1}>- {item.numbers} this.changeBookCount(index,1)}>+ changeBookCount(index,count){ const newBooks =[...this.state.books] newBooks[index].numbers +=count this.setState({ books:newBooks }) }删除功能 this.removeItem(index)}>移除 removeItem(index){ this.setState({ books:this.state.books.filter((item,indey)=>index !=indey) }) }总价 总价格:{this.getTotalprice()} getTotalprice(){ let totalPrice = this.state.books.reduce((pre,item)=>{ return pre+item.price * item.numbers },0) return formatPrice(totalPrice)} 最后附上所有代码 function formatPrice(price){ if(typeof price !=="number"){ price = Number("aaa") || 0 } return "¥"+ price.toFixed(2) } class Movie extends React.Component{ constructor(){ super() this.state={ books:[ {id:1,name:"《算法导论》",datas:'2006-9',price:25,numbers:1}, {id:2,name:"《编程艺术》",datas:'2006-9',price:45,numbers:1}, {id:3,name:"《代码大全》",datas:'2006-9',price:15,numbers:1}, {id:4,name:"《天演论》",datas:'2006-9',price:115,numbers:1}, ], } } renderBooks(){ return( 书籍名称 出版日期 价格 购买数量 操作 { this.state.books.map((item,index)=>{ return ( {index+1} {item.name} {item.datas} {formatPrice(item.price)} this.changeBookCount(index,-1)} disabled={item.numbers ==1}>- {item.numbers} this.changeBookCount(index,1)}>+ this.removeItem(index)}>移除 ) }) } 总价格:{this.getTotalprice()} ) } renderNone(){ return 购物车为空 } render() { const {books} = this.state return books.length ==0?this.renderNone():this.renderBooks() } changeBookCount(index,count){ const newBooks =[...this.state.books] newBooks[index].numbers +=count this.setState({ books:newBooks }) } removeItem(index){ this.setState({ books:this.state.books.filter((item,indey)=>index !=indey) }) } // getTotalprice(){ // 1.第一种 // let totalPrice = 0; // for(let i of this.state.books){ // totalPrice +=i.price * i.numbers // } // return formatPrice(totalPrice) // } //2.第二种 getTotalprice(){ let totalPrice = this.state.books.reduce((pre,item)=>{ return pre+item.price * item.numbers },0) return formatPrice(totalPrice) } } ReactDOM.render( ,document.getElementById('app') ) |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |