1. 购物车需求说明
list data展示到列表中 每个item的通过±按钮来控制购买的数据量 删除按钮可以删除当前的item Total Price计算当前购物车的总的价格
使用到的data list
const books = [ { id : 1 , name : 'introduction to algorithms' , date : '2006-9' , price : 85.00 , count : 1 } , { id : 2 , name : 'The Art of UNIX Programming' , date : '2006-2' , price : 59.00 , count : 1 } , { id : 3 , name : 'Programming pearls' , date : '2008-10' , price : 39.00 , count : 1 } , { id : 4 , name : 'Complete code' , date : '2006-3' , price : 128.00 , count : 1 } , ]
2. 项目code
<! DOCTYPE html >
< html lang = " en" >
< head> < meta charset = " UTF-8" > < meta http-equiv = " X-UA-Compatible" content = " IE=edge" > < meta name = " viewport" content = " width=device-width, initial-scale=1.0" > < title> shop car demo</ title> < style> table { border-collapse : collapse; text-align : center; } thead { background-color : #f2f2f2; } td, th { padding : 10px 16px; border : 1px solid #aaa; } </ style>
</ head>
< body> < div id = " root" > </ div> < script src = " ../../lib/react.js" > </ script> < script src = " ../../lib/react-dom.js" > </ script> < script src = " ../../lib/babel.js" > </ script> < script src = " ./data.js" > </ script> < script type = " text/babel" > class App extends React. Component { constructor ( ) { super ( ) this . state = { books : books} } increment ( index ) { const newBooks = [ ... this . state. books] newBooks[ index] . count += 1 this . setState ( { books : newBooks } ) } decrement ( index ) { const newBooks = [ ... this . state. books] newBooks[ index] . count -= 1 this . setState ( { books : newBooks } ) } deleteItem ( index ) { const newBooks = [ ... this . state. books] newBooks. splice ( index, 1 ) this . setState ( { books : newBooks } ) } render ( ) { const { books } = this . statereturn ( < div> < table> < thead> < tr> < td> Order< / td> < td> Name< / td> < td> Publish Date< / td> < td> Price< / td> < td> Bought Sum< / td> < td> Operation< / td> < / tr> < / thead> < tbody> { books. map ( ( item, index ) => { return ( < tr key= { item. id } > < td> { index + 1 } < / td> < td> { item. name } < / td> < td> { item. date } < / td> < td> { '$' + item. price } < / td> < td> < button disabled= { item. count <= 1 } onClick= { ( ) => { this . decrement ( index) } } > - < / button> { item. count } < button onClick= { ( ) => { this . increment ( index) } } > + < / button> < / td> < td> < button onClick= { ( ) => { this . deleteItem ( index) } } > Delete< / button> < / td> < / tr> ) } ) } < / tbody> < / table> < h2> Total Price: $ { books. reduce ( ( preValue, item ) => preValue + item. count * item. price, 0 ) } < / h2> < / div> ) } } const root = ReactDOM. createRoot ( document. querySelector ( "#root" ) ) root. render ( < App/ > ) </ script> </ body>
</ html>