React-Native 는 Mobx 를 사용 하여 카 트 기능 을 실현 합 니 다.

업무 중 에 카 트 를 사 는 장면 은 매우 흔 하 다.본 고 는 React-Native 와 Mobx 를 바탕 으로 두 가지 카 트 예 를 실현 한다.
그 중에서 후기 에는 애니메이션 등 다른 것 이 추가 된다.이번 기 에는 먼저 기초 기능 을 실현 한다.
2.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>
    );
  }
}

3.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;
      }
    }
  }
}

4:
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);

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기