邂逅react(六)-jsx小案例分享

分享一个react的经典小案例~~~
里面把很多jsx的用法都串起来了,不啰嗦了上干货

  
    
class App extends React.Component{
       constructor(){
           super()
           this.state={
               arrLists:[//数据
                   {id:'d1',name:'女上衣',price:200,madeby:'棉质',count:0,prices:0},
                   {id:'d2',name:'裙子',price:300,madeby:'涤纶',count:0,prices:0},
                   {id:'d3',name:'睡衣',price:400,madeby:'桑蚕丝',count:0,prices:0},
                   {id:'d4',name:'裤子',price:150,madeby:'混合',count:0,prices:0},
                   {id:'d5',name:'袜子',price:10,madeby:'腈纶',count:0,prices:0}
               ]                
           }
           
       }
        render(){
            return (
                
{this.state.arrLists.map((item,index)=>{//map遍历数组对象的每一项 return {/*绑定点击事件,箭头函数的形式绑定this,传入按钮类型参数判断当前按钮增加还是减少*/} })}
类型 价格 材质 数量 结算价
{item.name} {item.price} {item.madeby} {item.count} {item.prices=item.price*item.count}
{/*获取价格*/}

总价:{this.getTotalPrice()}

) } changeCount(index,type,count,price,prices){ console.log(index,type,count,price,prices) if(type=='add'){ this.setState({ count:this.state.arrLists[index].count++, }) }else if(type=='decrease'&&count>0){//判断按钮类型 避免减到负数 this.setState({ count:this.state.arrLists[index].count--, prices:count*price }) } } getTotalPrice(){ let totalPrice=0 for(let item of this.state.arrLists){//for of方法遍历获取对象里面的属性 totalPrice+=item.prices } return totalPrice } } ReactDOM.render(,document.getElementById('root'))

image.png

小结:这个小案例包括以下知识点:事件绑定,传参,获取和改变state里面的值,条件渲染,对象的属性遍历等。
今天的案例分享完毕 谢谢阅读

你可能感兴趣的:(javascript,前端,react.js,jsx)