Detailed explanation of the use of React list bar and shopping cart components

Detailed explanation of the use of React list bar and shopping cart components

This article example shares the specific code of React list bar and shopping cart components for your reference. The specific content is as follows

1. Component Introduction

Merchant details interface (StoreDetail component):

import React from 'react';
import axios from 'axios';
import GoBack from '../smallPage/GoBack';
import '../../Assets/css/storeDetail.css';
import MenuList from '../../Mock/MenuList';
import Order from '../menuPage/Order';
import Evaluate from '../menuPage/Evaluate';
import Business from '../menuPage/Business';

class StoreDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {  
            food:null,
            menulist:MenuList
        };
    }
    componentDidMount(){
        axios.get("/food").then((res)=>{
            this.setState({
                food:res.data.result.data
            });
            console.log(this.state.food);
        });
    }
    userSelect=(index)=>{
        MenuList.forEach((val,key)=>{
            val.isshow=false;
            if(key===index){
                val.isshow=true;
            }
        });
        this.setState({
            menulist:MenuList
        });
    }
    render() {
        return (
            this.state.food?
                <div>
                    <GoBack title={this.state.food.poi_info.name}/>
                    <div className="foodimage">
                        <img src={this.state.food.poi_info.pic_url} alt=""/>
                        <img src={this.state.food.poi_info.head_pic_url} alt=""/>
                        <span>{this.state.food.poi_info.name}</span>
                    </div>
                    <div>
                        <ul className="menulist">
                            {
                                this.state.menulist.map((value,index)=>{
                                    return (
                                        <li key={index} onClick={this.userSelect.bind(this,index)}>
                                            {value.title}
                                            <span className={value.isshow?'foodline':''}></span>
                                        </li>
                                    )
                                })
                            }
                        </ul>
                    </div>
                    {
                        this.state.menulist.map((value,index)=>{
                            if(value.isshow&&index===0){
                                return <Order toprice={this.state.food.poi_info.shipping_fee_tip} orderlist={this.state.food.food_spu_tags} key={index}/>
                            }else if(value.isshow&&index===1){
                                return <Evaluate key={index}/>
                            }else if(value.isshow&&index===2){
                                return <Business key={index}/>
                            }else{
                                return '';
                            }
                        })
                    }
                </div>
            :''
        );
    }
}

export default StoreDetail;

Order interface (Order component):

import React from 'react';
import '../../Assets/css/order.css';
import AddCut from '../smallPage/AddCut';
import Cart from '../smallPage/Cart';

class Order extends React.Component {
    constructor(props) {
        super(props);
        this.state = {  
            list:[],
            leftindex:0
        };
    }
    scrollRight=(e)=>{
        let scrolltop=e.target.scrollTop;
        let listheight=this.state.list;
        for(let i=0;i<listheight.length-1;i++){
            if(scrolltop<listheight[i]){
                // When sliding, take the first set in the array and modify the index value this.setState({
                    leftindex:i
                });
                break;
            }else if(scrolltop>=listheight[i]&&scrolltop<listheight[i+1]){
                // When the right sliding value is greater than half of the total height, the left index needs to go down if (i+1>=listheight.length/2) {
                    // Get the ul on the left and move its scrollTop down this.refs.leftul.scrollTop=listheight[i+1];
                }else{
                    // Move the scrollTop upwards this.refs.leftul.scrollTop=0;
                }
                this.setState({
                    leftindex:i+1
                });
                break;
            }
        }
    }
    // When the user clicks, change the color of the current index userClick=(index)=>{
        this.setState({
            leftindex:index
        });
        this.refs.order_scroll.scrollTop=index-1>=0?this.state.list[index-1]:0;
    }
    componentDidMount(){
        let order_block = document.getElementsByClassName("order_block");
        let listinfo=this.state.list;
        // Loop through the divs, get the offset of each div, and then push it into this.state to modify and display it. After modification, get listinfo
        // If it is the first div, only take its own offset; otherwise, take its own offset + listinfo[i-1] for(let i=0;i<order_block.length;i++){
            if(i===0){
                listinfo.push(order_block[i].offsetHeight);
            }else{
                listinfo.push(order_block[i].offsetHeight+listinfo[i-1]);
            }
        }
        this.setState({
            list:listinfo
        });
        // console.log(listinfo); (11) [550, 612, 1284, 1712, 2628, 5496, 7083, 8609, 9099, 9465, 10747]
    }
    //Call the forced refresh method in the child component Cart, and execute the method in the AddCut component refComponent=()=>{
        let ele = this.refs.cart;
        ele.update();
    }
    render() {
        return (
            <div className="order">
                <div className="order_left">
                    <ul ref="leftul">
                        {
                            this.props.orderlist.map((value,index)=>{
                                return (
                                    // Determine the color of the left li according to the index<li onClick={this.userClick.bind(this,index)} className={this.state.leftindex===index?'leftli leftli_color':'leftli'} key={index}>
                                        <img src={value.icon} alt=""/>
                                        <span>{value.name}</span>
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>
                <div onScroll={this.scrollRight} className="order_right">
                    <div ref="order_scroll" className="order_scroll">
                        {
                            this.props.orderlist.map((value,index)=>{
                                return (
                                    <div className="order_block" key={index}>
                                        <ul>
                                            {
                                                value.spus.map((v,k)=>{
                                                    return (
                                                        <li key={k}>
                                                            <div className="order_block_img">
                                                                <img src={v.picture} alt=""/>
                                                            </div>
                                                            <div className="order_block_word">
                                                                <div className="order_block_word_name">{v.name}</div>
                                                                <div className="order_block_word_zan">{v.praise_content}</div>
                                                                <div className="order_block_word_price">
                                                                    <span>¥{v.min_price}</span>/piece<AddCut parent={this} name={v.name} price={v.min_price}/>
                                                                </div>
                                                            </div>
                                                        </li>
                                                    )
                                                })
                                            }
                                        </ul>
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
                <Cart ref="cart" toprice={this.props.toprice}/>
            </div>
        );
    }
}

export default Order;

Add and subtract pages (AddCut component):

import React from 'react';
import '../../Assets/css/addCut.css';
import CartData from '../../Mock/CartData';

class AddCut extends React.Component {
    constructor(props) {
        super(props);
        this.state = {  
            num:0
        };
    }
    userAdd=()=>{
        let addnum=this.state.num;
        addnum++;
        this.setState({
            num:addnum
        });
        this.addCart(addnum);
        this.props.parent.refComponent();
    }
    userCut=()=>{
        let cutnum=this.state.num;
        cutnum--;
        if(cutnum<0){
            cutnum=0;
        }
        this.setState({
            num:cutnum
        });
        this.addCart(cutnum);
        this.props.parent.refComponent();
    }
    addCart=(num)=>{
        // Generate an object collection let list={
            name:this.props.name,
            price:this.props.price,
            num:num
        };
        let same=false;
        if(CartData.length===0){
            CartData.push(list);
        }
        for(let i=0;i<CartData.length;i++){
            if(CartData[i].name===this.props.name){
                CartData[i].num=num;
                same=true;
            }
        }
        if(!same){
            CartData.push(list);
        }
    }
    render() {
        return (
            <div className="addcut">
                <img onClick={this.userCut} className={this.state.num>0?'show':'showhidden'} src={require("../../Assets/image/minus.edae56b865f90527f2657782f67d9c3e.png")} alt=""/>
                <span className={this.state.num>0?'show':'showhidden'}>{this.state.num}</span>
                <img onClick={this.userAdd} src={require("../../Assets/image/plus.af10af5a9cee233c612b3cff5c2d70cd.png")} alt=""/>
            </div>
        );
    }
}

export default AddCut;

Shopping cart page (Cart component):

import React from 'react';
import '../../Assets/css/cart.css';
import CartData from '../../Mock/CartData';

class Cart extends React.Component {
    constructor(props) {
        super(props);
        this.state = {  
            cart:[],
            totalprice:0
        };
    }
    update=()=>{
        // Read data this.setState({
            cart:CartData
        });
        // Calculate the total price let prices=0;
        for(let i=0;i<CartData.length;i++){
            prices+=CartData[i].price*CartData[i].num;
        }
        this.setState({
            totalprice:prices
        });
    }
    render() {
        return (
            <div className="cart">
                <div className="cart_left">
                    <img src={require("../../Assets/image/shop-icon.3a615332a0e634909dc3aa3a50335c8f.png")} alt=""/>
                    <span>¥{this.state.totalprice}</span><br/>
                    <span>{this.props.toprice} is also required</span>
                </div>
                <div className="cart_right">Go to checkout</div>
            </div>
        );
    }
}

export default Cart;

2. Effect display

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • React implements clicking to delete the corresponding item in the list
  • React Native custom pull-down refresh pull-up loaded list example
  • React Native indexed city list component example code
  • React mobile terminal implements the sample code of swiping left to delete the list
  • React learning notes: list rendering example detailed explanation
  • Usage of ReactNative ListView
  • React-native sample code to implement the shopping cart sliding deletion effect
  • React-Native uses Mobx to implement shopping cart function

<<:  Detailed steps to install MySQL 5.6 X64 version under Linux

>>:  Implementation of Nginx configuration of multi-port and multi-domain name access

Recommend

How to optimize MySQL indexes

1. How MySQL uses indexes Indexes are used to qui...

WeChat applet development practical skills: data transmission and storage

Combining the various problems I encountered in m...

22 Vue optimization tips (project practical)

Table of contents Code Optimization Using key in ...

Talk about how to identify HTML escape characters through code

Occasionally you'll see characters such as &#...

Problems and solutions when installing MySQL8.0.13 on Win10 system

Operating system: Window10 MySQL version: 8.0.13-...

React passes parameters in several ways

Table of contents Passing parameters between pare...

The implementation principle of Mysql master-slave synchronization

1. What is MySQL master-slave synchronization? Wh...

React native realizes the monitoring gesture up and down pull effect

React native implements the monitoring gesture to...

A more elegant error handling method in JavaScript async await

Table of contents background Why error handling? ...

innerHTML Application

Blank's blog: http://www.planabc.net/ The use...

Implementation of debugging code through nginx reverse proxy

background Now the company's projects are dev...