React-Native使用Mobx实现购物车功能


Posted in Javascript onSeptember 14, 2017

在工作中,购物车场景非常常见。本文实现基于React-Native和Mobx实现两种购物车例子。

其中,后期会加入动画等其他。本期先实现基础功能。

二:基于State实现购物车

1-:ShoppingCarPage.js

export default class ShoppingCarPage extends Component {
  static navigationOptions = {
    headerTitle : '基于State购物车',
  };

  constructor(props) {
    super(props);
    this.state = {
      allSelecte : data.isAllSelect,
      totalMoney : data.totalMoney,
    }

  };

  getMoney = (m) => {
    this.state.totalMoney=this.state.totalMoney+m;
    //this.state.totalMoney += m;
    data.totalMoney = this.state.totalMoney;
    this.setState({
      totalMoney : this.state.totalMoney
    });

    let i = 0;
    data.datas.map((item) => {
      if (item.isSelect != true) {
        i += 1;
      }
    });
    if (i == 0) {
      data.isAllSelect = true;
      this.setState({ allSelecte : true })
    }
    else {
      data.isAllSelect = false;
      this.setState({ allSelecte : false })
    }
  };

  renderItem = (item) => {
    return (
      <ShoppingItemComponent
        itemData={item}
        money={this.getMoney}
      />
    )
  };

  allSelect = () => {
    data.totalMoney = 0;
    data.isAllSelect = !data.isAllSelect;
    this.state.totalMoney = 0;
    DeviceEventEmitter.emit('allSelect', !this.state.allSelecte);
    this.setState({ allSelecte : !this.state.allSelecte })
  };

  separatorView = () => {
    return (
      <View style={{ height : 10, backgroundColor : '#e9e9e9' }}/>
    )
  };

  keyExtractor = (item) => item.name;

  render() {
    let { allSelecte, totalMoney } = this.state;
    return (
      <View style={styles.container}>
        <FlatList data={data.datas}
             ItemSeparatorComponent={this.separatorView}
             renderItem={({ item }) => this.renderItem(item)}
             keyExtractor={ this.keyExtractor }
        />
        <View style={styles.tool}>
          <View style={{ flex : 1, flexDirection : 'row', alignItems : 'center' }}>
            <TouchableOpacity style={styles.select} onPress={ this.allSelect }>
              <Image source={allSelecte ? require('./imgs/login_radio_selected.png') : require('./imgs/login_radio_normall.png')}/>
              <Text style={{ marginLeft : 3 }}>全选</Text>
            </TouchableOpacity>
            <Text style={styles.allMoneyText}>
              ¥{this.state.totalMoney}
            </Text>
          </View>
          <TouchableOpacity style={styles.balance}>
            <Text style={styles.balanceText}>去结算</Text>
          </TouchableOpacity>
        </View>


      </View>
    );
  }
}

2-:ShoppingItemComponent.js

export default class ShoppingItemComponent extends Component {

  static propTypes = {
    itemData : PropTypes.object.isRequired,
    money : PropTypes.func,
  };

  static defaultProps = {
    money : () => null,
  };

  componentDidMount() {
    this.subscription = DeviceEventEmitter.addListener('allSelect', (isSelAll) => {
      this.props.itemData.isSelect = isSelAll;
      this.setState({ isSel : isSelAll });
      if (isSelAll) {
        this.setMoney(this.state.money * this.state.selNum);
      }

    })
  };

  componentWillUnmount() {
    this.subscription && this.subscription.remove();
  };

  constructor(props) {
    super(props);
    this.state = {
      isSel : this.props.itemData.isSelect,
      selNum : this.props.itemData.count,
      money : this.props.itemData.money,
      name : this.props.itemData.name,
      description : this.props.itemData.description,
      img : this.props.itemData.img,
    }
  };

  itemSelect = (item) => {
    this.setState({isSel :!this.state.isSel},()=>{
      if (this.state.isSel) {
        this.setMoney(this.state.money * this.state.selNum)
      }
      else {
        this.setMoney(-this.state.money * this.state.selNum)
      }
    });
  };

  itemIncrease = (i) => {
    i++;
    this.setState({selNum : i},()=>{
      if (this.state.isSel) {
        this.setMoney(this.state.money)
      }else{
        this.setState({isSel :true});
        this.setMoney(this.state.money * this.state.selNum);
      }
      this.props.itemData.count = i;
    });
  };

  itemReduce = (i) => {
    if (i <= 1) {
      if(this.state.isSel){
        this.setState({isSel :!this.state.isSel});
        this.setMoney(-this.state.money)
      }
      return;
    }
    i--;
    this.setState({ selNum : i },()=>{
      if (this.state.isSel) {
        this.setMoney(-this.state.money)
      }else{
        this.setState({isSel :true});
        this.setMoney(this.state.money * this.state.selNum);
      }
      this.props.itemData.count = i;
    });

  };

  setMoney = (money) => {
    if (this.props.money) {
      this.props.money(money);
    }
  };

  render() {
    let { itemData } = this.props;
    let { isSel, selNum, money, name, description, img } = this.state;
    return (
      <View style={ styles.container }>
        <TouchableOpacity
          style={{ marginLeft : 15 }}
          onPress={() => this.itemSelect(itemData)}>
          <Image source={isSel ?
            require('./imgs/login_radio_selected.png')
            : require('./imgs/login_radio_normall.png')}/>
        </TouchableOpacity>
        <Image style={ styles.icon } source={{ uri : img }}/>
        <View style={ styles.right }>
          <Text style={ styles.nameStyle } numberOfLines={ 2 }>{ name }</Text>
          <Text style={ styles.descriptionStyle } numberOfLines={1}>{ description }</Text>
          <View style={ styles.right_bot}>
            < Text style={ styles.moneyStyle }>¥{ money }</Text>
            <View style={ styles.numControllStyle }>

              <TouchableOpacity style={ styles.reduceStyle } onPress={() => this.itemReduce(selNum)}>
                <Text style={{ color : selNum <= 1 ? 'red' : 'black' } }>-</Text>
              </TouchableOpacity>
              <View style={ styles.numberViewStyle }>
                <Text style={ styles.numberStyle }>{ selNum }</Text>
              </View>
              <TouchableOpacity style={ styles.increaseStyle } onPress={() => this.itemIncrease(selNum)}>
                <Text>+</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </View>
    );
  }
}

三:基于Mobx实现购物车

1-:MobxShoppingCarPage.js

@observer
export default class MobxShoppingCarPage extends Component {
  static navigationOptions = {
    headerTitle : '基于MobX购物车',
  };

  constructor(props) {
    super(props);
    this.data = new MobxStore();
  };

  componentDidMount() {
    this.data.replace(jsonData)
  };

  @action
  allSelect = () => {
    DeviceEventEmitter.emit('allSelect', !this.data.itemData.isAllSelect);
    this.data.selectAll();
  };

  renderItem = (item) => {
    return (
      <MobxShopItemComponent itemData={ item } data={ this.data }/>
    )
  };

  separatorView = () => {
    return (
      <View style={{ height : 10, backgroundColor : '#e9e9e9' }}/>
    )
  };

  keyExtractor = (item) => item.name;

  render() {
    return (
      <View style={ styles.container }>
        <FlatList data={ this.data.itemData.datas }
             ItemSeparatorComponent={ this.separatorView }
             renderItem={ ({ item }) => this.renderItem(item) }
             keyExtractor={ this.keyExtractor }
        />
        <View style={ styles.tool }>
          <View style={{ flex : 1, flexDirection : 'row', alignItems : 'center' }}>
            <TouchableOpacity style={ styles.select } onPress={ this.allSelect }>
              <Image source={ this.data.itemData.isAllSelect ?
                require('../imgs/login_radio_selected.png')
                : require('../imgs/login_radio_normall.png') }/>
              <Text style={{ marginLeft : 3 }}>全选</Text>
            </TouchableOpacity>
            <Text style={ styles.allMoneyText }>
              ¥{ this.data.itemData.totalMoney }
            </Text>
          </View>
          <TouchableOpacity style={ styles.balance } onPress={ this.allSelect }>
            <Text style={ styles.balanceText }>去结算</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

2-:MobxShopItemComponent.js

@observer
export default class MobxShopItemComponent extends Component {

  static propTypes = {
    itemData : PropTypes.object.isRequired,
    data : PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.itemData = this.props.itemData;
  }

  componentDidMount() {
    this.subscription = DeviceEventEmitter.addListener('allSelect', (isSelAll) => {
      this.itemData.isSelect = isSelAll;
    })
  };

  componentWillUnmount() {
    this.subscription && this.subscription.remove();
  };

  @action
  selectPress = () => {
    this.itemData.isSelect = !this.itemData.isSelect;
    let money = this.itemData.money * this.itemData.count;
    if (this.itemData.isSelect) {
      this.props.data.increase(money);
    }
    else {
      this.props.data.reduce(money)
    }
    this.props.data.itemPress();
  };

  @action
  increase = () => {
    this.itemData.count += 1;
    if (this.itemData.isSelect) {
      this.props.data.increase(this.itemData.money);
    }else{
      this.itemData.isSelect = !this.itemData.isSelect;
      this.props.data.increase(this.itemData.money * this.itemData.count);
    }

  };

  @action
  reduce = () => {
    if (this.itemData.count <= 1) {
      if(this.itemData.isSelect){
        this.itemData.isSelect = !this.itemData.isSelect;
        this.props.data.reduce(this.itemData.money);
      }
      return;
    }
    this.itemData.count -= 1;
    if (this.itemData.isSelect) {
      this.props.data.reduce(this.itemData.money);
    }
  };

  render() {
    return (
      <View style={ styles.container }>
        <TouchableOpacity
          style={{ marginLeft : 15 }}
          onPress={ this.selectPress }>
          <Image source={ this.itemData.isSelect ?
            require('../imgs/login_radio_selected.png')
            : require('../imgs/login_radio_normall.png') }/>
        </TouchableOpacity>
        <Image style={ styles.icon } source={{ uri : 'https://img10.360buyimg.com/n7/jfs/t4063/153/323373745/444727/87c24f22/58b11156N9be178c2.jpg' }}/>
        <View style={ styles.right }>
          <Text style={ styles.nameStyle } numberOfLines={ 2 }>{ this.itemData.name }</Text>
          <Text style={ styles.descriptionStyle } numberOfLines={1}> { this.itemData.description }</Text>
          <View style={ styles.right_bot}>
            < Text style={ styles.moneyStyle }>¥{ this.itemData.money }</Text>
            <View style={ styles.numControllStyle }>
              <TouchableOpacity style={ styles.reduceStyle } onPress={ this.reduce }>
                <Text style={{ color : this.itemData.count <= 1 ? 'red' : 'black' } }>-</Text>
              </TouchableOpacity>
              <View style={ styles.numberViewStyle }>
                <Text style={ styles.numberStyle }>{ this.itemData.count }</Text>
              </View>
              <TouchableOpacity style={ styles.increaseStyle } onPress={ this.increase }>
                <Text>+</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </View>
    );
  }
};

3-:MobxStore.js

import { observable, action, computed, autorun } from 'mobx';

export default class MobxStore {
  @observable
  itemData = {}

  //设置数据
  replace = (data) => {
    this.itemData = data;
  }

  //按下的反选
  itemPress = () => {
    let i = 0;
    this.itemData.datas.map((item) => {
      if (item.isSelect != true) {
        i += 1;
      }
    });
    if (i == 0) {
      this.itemData.isAllSelect = true;
    }
    else {
      this.itemData.isAllSelect = false;
    }
  }

  //加
  increase = (money) => {
    this.itemData.totalMoney += money;
  }

  //减
  reduce = (money) => {
    this.itemData.totalMoney -= money;
  }

  //全选
  selectAll = () => {
    this.itemData.isAllSelect = !this.itemData.isAllSelect;
    this.itemData.totalMoney = 0;
    if (this.itemData.isAllSelect) {
      for (let i = 0;
        i < this.itemData.datas.length;
        i++) {
        this.itemData.totalMoney += this.itemData.datas[ i ].money * this.itemData.datas[ i ].count;
      }
    }
  }
}

四:

1-:代码github地址:https://github.com/erhutime/React-Navigation-All/tree/master/All/jscode/shoppingcar/src

2-:下载完成后,修改index.ios.js:入口文件如下:

运行效果如下:

import App from './jscode/shoppingcar/src/App'
AppRegistry.registerComponent('All', () => App);

React-Native使用Mobx实现购物车功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
js中将具有数字属性名的对象转换为数组
Mar 06 Javascript
在jQuery1.5中使用deferred对象 着放大镜看Promise
Mar 12 Javascript
JS焦点图切换,上下翻转
May 12 Javascript
JavaScript中的作用域链和闭包
Jun 30 Javascript
document.write的几点使用心得
May 14 Javascript
AngularJS基础 ng-keydown 指令简单示例
Aug 02 Javascript
简单实现js点击展开二级菜单功能
May 16 Javascript
微信小程序分享功能之按钮button 边框隐藏和点击隐藏
Jun 14 Javascript
JS实现用特殊符号替换字符串的中间部分区域的实例代码
Jul 24 Javascript
Vue CLI3 如何支持less的方法示例
Aug 29 Javascript
jQuery实现的卷帘门滑入滑出效果【案例】
Feb 18 jQuery
小程序如何构建骨架屏
May 29 Javascript
JavaScript requestAnimationFrame动画详解
Sep 14 #Javascript
SVG动画vivus.js库使用小结(实例代码)
Sep 14 #Javascript
浅谈AngularJS中使用$resource(已更新)
Sep 14 #Javascript
jQuery plugin animsition使用小结
Sep 14 #jQuery
angular.extend方法的具体使用
Sep 14 #Javascript
浅谈angular.copy() 深拷贝
Sep 14 #Javascript
说说AngularJS中的$parse和$eval的用法
Sep 14 #Javascript
You might like
盘点被央视点名过的日本动画电影 一部比一部强
2020/03/08 日漫
PHP中的按位与和按位或操作示例
2014/01/27 PHP
javascript之函数直接量(function(){})()
2007/06/29 Javascript
网页加载时页面显示进度条加载完成之后显示网页内容
2012/12/23 Javascript
javascript中的return和闭包函数浅析
2014/06/06 Javascript
浅谈JavaScript事件的属性列表
2015/03/01 Javascript
JQuery实现可直接编辑的表格
2015/04/16 Javascript
javascript对象的相关操作小结
2016/05/16 Javascript
react-native中ListView组件点击跳转的方法示例
2017/09/30 Javascript
node vue项目开发之前后端分离实战记录
2017/12/13 Javascript
原生JS实现的碰撞检测功能示例
2018/05/18 Javascript
vue中使用codemirror的实例详解
2018/11/01 Javascript
elementUi vue el-radio 监听选中变化的实例代码
2019/06/28 Javascript
python 控制语句
2011/11/03 Python
给你选择Python语言实现机器学习算法的三大理由
2017/11/15 Python
Django admin美化插件suit使用示例
2017/12/12 Python
python 并发编程 非阻塞IO模型原理解析
2019/08/20 Python
pytorch 彩色图像转灰度图像实例
2020/01/13 Python
Tensorflow 使用pb文件保存(恢复)模型计算图和参数实例详解
2020/02/11 Python
Python实现对adb命令封装
2020/03/06 Python
详解淘宝H5 sign加密算法
2020/08/25 HTML / CSS
爱尔兰旅游网站:ebookers.ie
2020/01/24 全球购物
沃尔玛加拿大:Walmart.ca
2020/03/02 全球购物
新浪网技术部笔试题
2016/08/26 面试题
大二自我鉴定范文
2013/10/05 职场文书
实习教师自我鉴定
2013/12/12 职场文书
大学校庆策划书
2014/01/31 职场文书
公司合作意向书
2014/04/01 职场文书
学习交流会主持词
2014/04/01 职场文书
数学教研活动总结
2014/07/02 职场文书
完整版商业计划书
2014/09/15 职场文书
房屋产权证明书
2015/06/19 职场文书
导游词之北京明十三陵
2019/10/28 职场文书
canvas绘制折线路径动画实现
2021/05/12 Javascript
MySQL Router实现MySQL的读写分离的方法
2021/05/27 MySQL
Win11怎么启动任务管理器?Win11启动任务管理器的几种方法
2021/11/23 数码科技