index.js
import React from 'react'
import ReactDOM from 'react-dom'
import CartSimple from './CartSimple'
const jsx = (
<div>
<h1>React Study</h1>
<CartSimple/>
</div>
);
//渲染组件
ReactDOM.render(jsx,document.getElementById("root"));
CartSimple组件
import React, { Component } from 'react'
function CartByMe(props) {
return (
<table>
<tbody>
{
props.cart.map((goods, i) => {
return (<tr key={i}>
<td >名称:{goods.tital} </td>
<td >总价格:{goods.price * goods.count} </td>
</tr>)
})
}
</tbody>
</table>
)
}
export default class CartSimple extends Component {
constructor(props) {
super(props)
this.state = {
goods: [],
price: "",
tital: '',
cart: []
}
}
componentDidMount() {
//发起请求
setTimeout(() => {
let goods = [
{ id: 1, tital: "React入门", price: 100 },
{ id: 2, tital: "React高级", price: 800 },
{ id: 3, tital: "React进阶", price: 600 },
{ id: 4, tital: "React精通", price: 200 },
];
this.setState({
goods
})
}, 1000);
}
handlePrice = e => {
this.setState(
{
price: e.target.value
}
);
}
handleTital = (e) => {
this.setState({
tital: e.target.value
})
}
addNewGood = (e) => {
if (this.state.tital && this.state.price) {
let lenMax = this.state.goods.length;
this.setState({
goods: [...this.state.goods, { id: lenMax + 1, tital: this.state.tital, price: this.state.price }]
})
}
}
addShop = (id) => {
const goods = this.state.goods.map((item) => {
if(item.id == id){
return item;
}
});
const good = goods.filter((item)=>{
if(item!=null){
return item;
}
})
const cartGoods = this.state.cart.find(v => v.tital === good[0].tital);
if (cartGoods) {
//已经在购物侧里面有了
const newCart = [...this.state.cart];
newCart.forEach((item) => {
if (item.id == id) {
item.count += 1;
}
})
this.setState({
cart: newCart
})
} else {
//第一次添加商品
this.setState({
cart: [...this.state.cart, {
active: true,
id: good[0].id,
tital: good[0].tital,
price: good[0].price,
count: 1
}]
})
}
}
render() {
return (
<div>
<h1>购物侧</h1>
<div>
<p>
<label htmlFor="tital">名字</label>
<input type="text" id="tital" value={this.state.tital} onChange={this.handleTital} />
</p>
<p>
<label htmlFor="price">价格</label>
<input type="text" id="price" value={this.state.price} onChange={this.handlePrice} />
</p>
<button onClick={this.addNewGood} value="添加">添加</button>
</div>
<ul>
{
this.state.goods.map((item) => {
return (
<li key={item.id}>
<span>名称:{item.tital}</span>
<span>价格:{item.price}</span>
<button onClick={() => this.addShop(item.id)} value="">添加购物侧</button>
</li>);
})
}
</ul>
<hr></hr>
<CartByMe cart={this.state.cart}></CartByMe>
</div>
)
}
}