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 相关文章推荐
学习ExtJS border布局
Oct 08 Javascript
仅Firefox中链接A无法实现模拟点击以触发其默认行为
Jul 31 Javascript
jQuery 数据缓存模块进化史详细介绍
Nov 19 Javascript
JS操作select下拉框动态变动(创建/删除/获取)
Jun 02 Javascript
jquery操作对象数组元素方法详解
Nov 26 Javascript
浅谈addEventListener和attachEvent的区别
Jul 14 Javascript
KnockoutJS 3.X API 第四章之数据控制流if绑定和ifnot绑定
Oct 10 Javascript
js代码实现下拉菜单【推荐】
Dec 15 Javascript
Javascript 实现全屏滚动实例代码
Dec 31 Javascript
jquery编写日期选择器
Mar 16 Javascript
使用Fullpage插件快速开发整屏翻页的页面
Sep 13 Javascript
JS+HTML实现的圆形可点击区域示例【3种方法】
Aug 01 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
php下使用iconv需要注意的问题
2010/11/20 PHP
php判断终端是手机还是电脑访问网站的思路及代码
2013/04/24 PHP
php实现的网络相册图片防盗链完美破解方法
2015/07/01 PHP
HTTP 304错误的详细讲解
2013/11/13 Javascript
通过复制Table生成word和excel的javascript代码
2014/01/20 Javascript
用js读、写、删除Cookie代码续篇
2014/12/03 Javascript
node.js中的fs.writeSync方法使用说明
2014/12/15 Javascript
javascript实现避免页面按钮重复提交
2015/01/08 Javascript
高性能JavaScript模板引擎实现原理详解
2015/02/05 Javascript
jQuery实现点击按钮文字变成input框点击保存变成文字
2016/05/09 Javascript
javascript中Number的方法小结
2016/11/21 Javascript
jQuery使用正则表达式替换dom元素标签用法示例
2017/01/16 Javascript
ES6中Array.copyWithin()函数的用法实例详解
2017/09/16 Javascript
使用vue.js在页面内组件监听scroll事件的方法
2018/09/11 Javascript
浅谈angularJs函数的使用方法(大小写转换,拷贝,扩充对象)
2018/10/08 Javascript
javascript设计模式 ? 代理模式原理与用法实例分析
2020/04/16 Javascript
JavaScript 中判断变量是否为数字的示例代码
2020/10/22 Javascript
纯Python开发的nosql数据库CodernityDB介绍和使用实例
2014/10/23 Python
浅谈python中的变量默认是什么类型
2016/09/11 Python
Centos7 Python3下安装scrapy的详细步骤
2018/03/15 Python
利用Python yagmail三行代码实现发送邮件
2018/05/11 Python
python中dict字典的查询键值对 遍历 排序 创建 访问 更新 删除基础操作方法
2018/09/13 Python
Python基于opencv实现的简单画板功能示例
2019/03/04 Python
在Python中获取操作系统的进程信息
2019/08/27 Python
详解pycharm自动import所需的库的操作方法
2020/11/30 Python
python中@property的作用和getter setter的解释
2020/12/22 Python
Python机器学习工具scikit-learn的使用笔记
2021/01/28 Python
大学生毕业求职简历的自我评价
2013/10/24 职场文书
村委会贫困证明
2014/01/14 职场文书
决心书范文
2014/03/11 职场文书
出纳会计岗位职责
2014/03/12 职场文书
行风评议整改报告
2014/11/06 职场文书
先进基层党组织材料
2014/12/25 职场文书
2016大学生社会实践心得体会范文
2016/01/14 职场文书
Python中常见的导入方式总结
2021/05/06 Python
HTML+CSS 实现顶部导航栏菜单制作
2021/06/03 HTML / CSS