Как добавить элементы в массив в React Native? - PullRequest
1 голос
/ 02 августа 2020

Я хочу добавить item.name, item.id, item.price в массив onClick кнопки. Кнопка находится в Flatlist, поэтому каждый раз, когда я хочу сохранить эти элементы в массиве и, наконец, мне нужны все эти элементы.

**enter code here**
import React, { Component } from 'react';
import {Text,View,FlatList, Modal,TouchableOpacity} from 'react-native';
import { Style } from './style';
import CustomButton from '../../custom-button/custom-button';
import { SafeAreaView } from 'react-native-safe-area-context';
import ModalComponent from '../Modal/ModalComponent';
import CustomIcon from '../CustomIcons/CustomIcon';

interface MenuItemsProps{
  menuArray:any[];
  category_name:string;
}
interface MenuItemsState{
  flag:number;
  visible:boolean;
  firstModalVisible2:boolean;
  firstModalVisible3:boolean;
  itemcount:number;
  cartArray:any[];// I want to add items in this array
 
}
export default class MenuItemsComponent extends Component<MenuItemsProps,MenuItemsState>{
    constructor(props:MenuItemsProps){
        super(props);
        this.state={
          flag:0,
          visible:false,
          firstModalVisible2:false,
          firstModalVisible3:false,
          itemcount:0,
          cartArray:[]
         
        }
    }
    componentDidMount(){
      {this.props.menuArray.map((data) => {
          {if(this.props.category_name==data.category_name)
            this.setState({
              flag:this.state.flag+1
            })}}
        )}     
    }

  
    render(){
    return (
        <SafeAreaView style={Style.paddingStyle}>  
          {this.state.flag!=0?
          <View>
          <Text style={Style.textStyle}>{this.props.category_name}</Text> 
          <FlatList
              data={this.props.menuArray}
              renderItem={({item}) =>(
                <View>
                  {item.category_name==this.props.category_name?
                  <View style={{paddingTop:7}}> 
                    <View  style={Style.menu_buttonStyle}>        
                        <View>
                          <Text style={Style.nameStyle}>{item.name}</Text>
                          <Text style={Style.priceStyle}>{'\u20B9'}{item.price}</Text>
                        </View>
                        <View>
                          <CustomButton //onthis button click
                          onPress={()=> 
                             this.setState({itemcount:this.state.itemcount+1})
                          }
                           text=" Add " outline={true} /> 
                         {/* {this.state.visible&& <ModalComponent  price={item.price} visible={this.state.visible} itemname={item.name}/> } */}
                        </View>
                    </View>
                    <Text style={Style.descriptionStyle}>{item.description}</Text>
                  </View>:null}
                </View>
              )}
              keyExtractor={item => item.id}  
          />



          </View>:null} 
          
        </SafeAreaView>
    );
  }
}

Это мой код

Я хочу добавить item.name, item.id, item.price в массив onClick of button. Кнопка находится в Flatlist, поэтому каждый раз, когда я хочу сохранить эти элементы в массиве и, наконец, мне нужны все эти элементы.

1 Ответ

0 голосов
/ 02 августа 2020

может быть, вам подойдет что-то вроде ниже.

import React, {Component} from 'react';
import {Text, View, FlatList, Modal, TouchableOpacity} from 'react-native';
import {Style} from './style';
import CustomButton from '../../custom-button/custom-button';
import {SafeAreaView} from 'react-native-safe-area-context';
import ModalComponent from '../Modal/ModalComponent';
import CustomIcon from '../CustomIcons/CustomIcon';

interface MenuItemsProps {
  menuArray: any[];
  category_name: string;
}
interface MenuItemsState {
  flag: number;
  visible: boolean;
  firstModalVisible2: boolean;
  firstModalVisible3: boolean;
  itemcount: number;
  cartArray: any[]; // I want to add items in this array
}
export default class MenuItemsComponent extends Component<
  MenuItemsProps,
  MenuItemsState,
> {
  constructor(props: MenuItemsProps) {
    super(props);
    this.state = {
      flag: 0,
      visible: false,
      firstModalVisible2: false,
      firstModalVisible3: false,
      itemcount: 0,
      categoryItems: [],
      cartArray: [],
    };
  }
  componentDidMount() {
    
    // Filter out items not in the selected category
    const categoryItems = this.props.menuArray.filter((item) => {
      return this.props.category_name == item.category_name;
    });

    this.setState({
      categoryItems: categoryItems,
    });
  }
  
  // Call this when you want to save all the cart items
  saveCartItems() { 
    const cartItems = this.state.cartArray;
    
    // Post cartItems to your app API
  }

  render() {
    return (
      <SafeAreaView style={Style.paddingStyle}>
        {this.state.categoryItems.length (
          <View>
            <Text style={Style.textStyle}>{this.props.category_name}</Text>
            <FlatList
              data={this.state.categoryItems}
              renderItem={({item}) => (
                <View>
                  {item.category_name == this.props.category_name ? (
                    <View style={{paddingTop: 7}}>
                      <View style={Style.menu_buttonStyle}>
                        <View>
                          <Text style={Style.nameStyle}>{item.name}</Text>
                          <Text style={Style.priceStyle}>
                            {'\u20B9'}
                            {item.price}
                          </Text>
                        </View>
                        <View>
                          <CustomButton
                            onPress={() =>
                              // Add the current list item to the array
                              this.setState({
                                
                                // Use the spread (...) operator to create a new array
                                // with all the existing items plus the new item
                                // then update cartArray with this new array
                                cartArray: [...this.state.cartArray, item]
                              })
                            }
                            text=" Add "
                            outline={true}
                          />
                          {/* {this.state.visible&& <ModalComponent  price={item.price} visible={this.state.visible} itemname={item.name}/> } */}
                        </View>
                      </View>
                      <Text style={Style.descriptionStyle}>
                        {item.description}
                      </Text>
                    </View>
                  ) : null}
                </View>
              )}
              keyExtractor={(item) => item.id}
            />
          </View>
        ) : null}
      </SafeAreaView>
    );
  }
}
...