使用react初步实现一个购物车小组件
下面是完成的状态
下面是代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border: 1px solid #eee;
border-collapse: collapse;
}
th,
td {
border: 1px solid #eee;
padding: 10px 16px;
text-align: center;
}
th {
background: #e5e5e5;
}
.count{
padding:0 10px;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="app"></div>
<!-- 引入依赖 -->
<script src="../react.development.js"></script>
<script src="../react-dom.development.js"></script>
<script src="../babel.min.js"></script>
<!-- 使用script编写react代码 -->
<script type="text/babel">
class App extends React.Component {
constructor() {
super()
this.state = {
books: [
{
id: 1,
name: '代码大全1',
date: '2005-3-19',
price: 128.00,
count: 1
},
{
id: 2,
name: '代码大全2',
date: '2005-3-19',
price: 128.00,
count: 1
},
{
id: 3,
name: '代码大全3',
date: '2005-3-19',
price: 128.00,
count: 1
},
{
id: 4,
name: '代码大全4',
date: '2005-3-19',
price: 128.00,
count: 1
}
]
}
}
renderBooks(){
return (
<div>
<table>
<thead>
<tr>
<th>序号</th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th></tr>
</thead>
<tbody>
{
this.state.books.map((item,index) => {
return (
<tr>
<td>{
index + 1}</td>
<td>{
item.name}</td>
<td>{
item.date}</td>
<td>{
item.price}</td>
<td>
<button disabled={
item.count <=1} onClick={
e=>this.changeCount(index,-1)}>-</button>
<span className="count">{
item.count}</span>
<button onClick={
e=>this.changeCount(index,+1)}>+</button>
</td>
<td>
<button onClick={
e=>this.remove(index)}>移除</button></td>
</tr>
)
})}
</tbody></table>
<h2>{
this.state.books.reduce((pre,item)=>{
return pre+item.price * item.count},0)}</h2>
</div>
)
}
renderEmpty(){
return <h2>购物车为空</h2>
}
render() {
return this.state.books.length? this.renderBooks() : this.renderEmpty()
}
remove(index){
this.setState({
books: this.state.books.filter((item,indey)=>{
return index !=indey
})
})
}
changeCount(index,count){
const arr = [...this.state.books]
arr[index].count = arr[index].count + count
this.setState({
books: arr
})
}
}
ReactDOM.render(<App />, document.getElementById("app"))
</script>
</body>
</html>