BuildBurger.js中添加BuildControls——按钮控制ingredient
注意点:
add和remove中调用state中的object需要使用深拷贝,否为为拷贝地址,为错误操作;
传入diable参数,在一个type添加个数为0时,屏蔽remove操作;
import React,{Component} from 'react';
import Aux from '../../hoc/Auxiliary';
import Burger from '../../components/Burger/Burger';
import BuildControls from '../../components/Burger/BuildControls/BuildControls';
const INGREDIENT_PRICES={
salad:20,
cheese:14,
meat:99,
bacon:17
};
class BurgerBuilder extends Component{
state ={
ingredients:{
salad:0,
bacon:0,
cheese:0,
meat:0
},
totalPrice:11
}
addIngredientHandler = (type)=>{
const getst={...this.state.ingredients};
getst[type]+=1;
let getprice = this.state.totalPrice;
getprice+=INGREDIENT_PRICES[type];
this.setState({
ingredients:getst,
totalPrice:getprice
});
}
removeIngredientHandler =(type)=>{
const getst={...this.state.ingredients};
getst[type]-=1;
let getprice = this.state.totalPrice;
getprice-=INGREDIENT_PRICES[type];
this.setState({
ingredients:getst,
totalPrice:getprice
});
}
render(){
const disabledInfo = {
...this.state.ingredients
};
for(let key in disabledInfo){
disabledInfo[key] = disabledInfo[key]<=0; //返回true false
}
return(
<Aux>
<Burger ingredients={this.state.ingredients}/>
<BuildControls
ingredientAdded={this.addIngredientHandler}
ingredientRmoved={this.removeIngredientHandler}
disabled={disabledInfo}
price={this.state.totalPrice}
/>
</Aux>
);
}
}
export default BurgerBuilder;
BuildControls.js
用map把需要添加的controls全部传入buildcontrol,并添加至下方;
import React from 'react';
import classes from './BuildControls.module.css';
import BuildControl from './BuildControl/BuildControl';
const controls=[
{label:'Salad',type:'salad'},
{label:'Bacon',type:'bacon'},
{label:'Cheese',type:'cheese'},
{label:'Meat',type:'meat'}
];
const buildControls =(props)=>(
<div className={classes.BuildControls}>
<p>Current Price: <strong>{props.price.toFixed(2)}</strong></p>
{controls.map((control)=>(
<BuildControl
key = {control.label}
label={control.label}
added={()=>props.ingredientAdded(control.type)}
removed={()=>props.ingredientRmoved(control.type)}
disabled={props.disabled[control.type]}
/>
))}
</div>
);
export default buildControls;
BuildControl.js
设置button属性,此为最小的element;
import React from 'react';
import classes from './BuildControl.module.css';
const buildControl = (props)=>{
return(
<div className={classes.BuildControl}>
<div className={classes.Label}>{props.label}</div>
<button
className={classes.Less}
onClick={props.removed}
disabled={props.disabled}
>Less</button>
<button
className={classes.More}
onClick={props.added}
>More</button>
</div>
)
};
export default buildControl;