Javascript React Native-更改每个项目的数量并显示总数

Javascript React Native-更改每个项目的数量并显示总数,javascript,react-native,expo,Javascript,React Native,Expo,我是这方面的新手,我想更改每件商品的数量,而不是下图所示的整件商品(是的,我知道,因为我正在使用单击状态作为文本上的值,傻瓜我),我该怎么做?我如何显示项目的总价格,而不是在价格之后加上价格?是因为绳子吗 这是我的密码 import React from 'react'; import { StyleSheet, Text, View, Image, Dimensions, TouchableOpacity, ScrollView, SafeAreaView, Alert, ActivityI

我是这方面的新手,我想更改每件商品的数量,而不是下图所示的整件商品(是的,我知道,因为我正在使用
单击
状态作为文本上的值,傻瓜我),我该怎么做?我如何显示项目的总价格,而不是在价格之后加上价格?是因为绳子吗

这是我的密码

import React from 'react';
import { StyleSheet, Text, View, Image, Dimensions, TouchableOpacity, ScrollView, SafeAreaView, Alert, ActivityIndicator, ImageBackground } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
import AsyncStorage from '@react-native-community/async-storage';
import { Ionicons, FontAwesome } from "@expo/vector-icons";
import * as Font from 'expo-font';
import RBSheet from "react-native-raw-bottom-sheet";
import Moment from 'moment';
import { WebView } from 'react-native-webview';
import HTML from 'react-native-render-html';
import NetInfo from "@react-native-community/netinfo";
import NumberFormat from 'react-number-format';
import * as Crypto from "expo-crypto";

import ApiUrl from "../../assets/utils/ApiUrl"
import AppData from "../../assets/utils/AppData"

const SLIDER_WIDTH = Dimensions.get('window').width;
const ITEM_WIDTH = Math.round(SLIDER_WIDTH * 0.7);
const ITEM_HEIGHT = Math.round(ITEM_WIDTH * 3 / 4);
let customFonts = {
  'Roboto': require('../../assets/fonts/Roboto.ttf'),
  'Titillium-Web': require('../../assets/fonts/TitilliumWeb.ttf'),
};

export default class PaymentStatus extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      fontsLoaded: false,
      loading: false,
      ticketLength: "",
      id: "",
      idUser: "",
      dataEventTicket: [],
      loadingEventTicket: false,
      ticketCart: [],
      ticketArray: [],
      clicks: 0
    }
  }

  async componentDidMount() {
    await Font.loadAsync(customFonts);
    const { navigation } = this.props
    await this.setState({
      idEvent: navigation.getParam("idEvent", ""),
      eventName: navigation.getParam("eventName", ""),
      eventLocation: navigation.getParam("eventLocation", ""),
      eventDate: navigation.getParam("eventDate", ""),
      eventTime: navigation.getParam("eventTime", ""),
      eventImg: navigation.getParam("eventImg", "")
    })
    this.initAsync();
    this.setState({ fontLoaded: true })
  }
  
  async componentWillUnmount() {
    this.setState({ loading: false })
  }
  
  initAsync = async () => {
    await this.loadEventTicket()
  };

  async loadEventTicket() {
    const id = "?id="+this.state.idEvent
    this.setState({ loadingEventTicket: true })
    await fetch(ApiUrl.getcategoryticket + id, {
      method: "GET",
      headers: new Headers({
        "Content-Type": "application/json",
        "Eventku-Api-Key": AppData.apiKey
      })
    }).then(response => response.json()).then(responseJson => {
      try {
        if (responseJson.status) {
          const data = responseJson.result
          this.setState({ 
            dataEventTicket: data.category,
          })
          for (var i=0; i < this.state.dataEventTicket.length; i++) {
            var joined = this.state.ticketArray.concat(this.state.dataEventTicket[i].id);
            this.setState({ ticketArray: joined })
          }
        }
      } catch ({ message }) {
        console.log(message);
        Alert.alert('', 'Terjadi kesalahan pada aplikasi')
      }
    }).catch(error => {
      console.log(error);
      Alert.alert('', 'Terjadi kesalahan pada aplikasi')
    })
    this.setState({ loadingEventTicket: false })
  }

  async _buyTicket() {
    // this.props.navigation.navigate("PaymentStatus", {
    //   id: item.id,
    //   eventName: item.event_name,
    //   eventAddress: item.event_address,
    //   eventDate: item.event_date,
    //   eventTime: item.event_time,
    //   orderID: item.order_id,
    //   grandTotal: item.grandtotal,
    //   ImageUrl: item.image_url
    // });
    this.props.navigation.navigate("TicketBuyerDetail");
  }

  async incrementItem(item) {
    var joined = this.state.ticketCart.concat(item.id);
    this.setState({ 
      // ticketCart: joined,
      clicks: this.state.clicks + 1,
      ticketCart: this.state.ticketCart + item.price,
    });
    console.log(this.state.ticketCart)
  }
  async decreaseItem(item) {
    if (this.state.clicks != 0 ) {
      this.setState({ clicks: this.state.clicks - 1 });
    }
  }

  render() {
    const dateFormat = Moment(this.state.eventDate).format('D MMMM YYYY')

    const EventTicket = () => (
      (this.state.loadingEventTicket && <ActivityIndicator
          style={{ flex: 1, alignContent: "center", height: 44,marginBottom:20 }}
          animating={this.state.loadingEventTicket}
          size="large"
          color="#32E0C4"
      />) ||
      <View>
        {this.state.dataEventTicket.map((item,index) => (
          <View style={{ flex: 1, flexDirection: "row", alignItems: "center" }} key={item.id}>
            <View style={{ flex: 1, flexDirection: "column", marginTop: 12, marginBottom: 12 }}>
              <Text style={styles.ticketTitleAvail}>{item.name}</Text>
              {item.type == "PAID" && 
                <NumberFormat value={item.price} displayType={'text'} thousandSeparator={true} prefix={'Rp '} renderText={value => <Text style={styles.ticketPriceAvail}>{value}</Text>}/>
              }
              {item.type == "FREE" && 
                <Text style={styles.ticketPriceAvail}>Gratis</Text>
              }
            </View>
            <TouchableOpacity onPress={() => {this.decreaseItem(item)}}>
              <Ionicons name="ios-remove-circle-outline" color={"#32E0C4"} size={24}/>
            </TouchableOpacity>
            {/* <TextInput
              keyboardType="number-pad"
              returnKeyType="done"
              value={this.state.clicks}
              onChangeText={clicks => this.setState({ clicks })}/> */}
              <Text style={{ marginHorizontal: 10 }}>{this.state.clicks}</Text>
            <TouchableOpacity onPress={() => {this.incrementItem(item)}}>
              <Ionicons name="ios-add-circle-outline" color={"#32E0C4"} size={24}/>
            </TouchableOpacity>
          </View>
        ))}
      </View>
    )

    return (
      <View style={styles.container}>
        <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false}>
          <View style={styles.eventHeader}>
            <ImageBackground
              style={styles.eventPictBg}
              resizeMode= "cover"
              source={this.state.eventImg ? { uri: this.state.eventImg } : null}
              blurRadius={4}/>
            <View style={{ flexDirection: "row", position: "absolute", marginLeft: 15 }}>
              <Image 
                style={styles.eventPict}
                resizeMode= "cover"
                source={this.state.eventImg ? { uri: this.state.eventImg } : null}/>
              <View style={{ marginLeft: 20, marginTop: 50 }}>
                <Text style={{ fontWeight: "bold", fontSize: 16, color: "#fff", marginTop: 5 }}>{this.state.eventName}</Text>
                <Text style={styles.eventDetail}>{this.state.eventLocation}</Text>
                <Text style={styles.eventDetail}>{dateFormat}</Text>
                <Text style={styles.eventDetail}>{this.state.eventTime}</Text>
              </View>
            </View>
          </View>
          <View style={{ flex: 1, marginHorizontal: 20, marginVertical: 10, padding: 8 }}>
            <EventTicket/>
          </View>
        </ScrollView>
        <View style={{ flexDirection: "row", justifyContent: "space-between", marginHorizontal: 20, marginBottom: 20 }}>
          <View style={{ alignSelf: "center" }}>
            <Text>Subtotal</Text>
            <Text>Rp. {this.state.ticketCart}</Text>
          </View>
          <TouchableOpacity style={{ backgroundColor: "#32E0C4", borderRadius: 10 }} onPress={() => this._buyTicket()}>
            <Text style={{ padding: 20, color: "#fff" }}>Beli Tiket</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    flex: 1
  },
  eventHeader: {
  },
  eventPictBg: {
    alignSelf: "center",
    height: 250,
    width: Dimensions.get('window').height
  },
  eventPict: {
    height: 250,
    width: 150
  },
  subHeader: {
    color: "#32E0C4"
  },
  eventDetail: {
    color: "#fff"
  },
  ticketPriceAvail: {
    // fontFamily: "Roboto",
    fontSize: 14,
    lineHeight: 21,
    letterSpacing: 0.15,
    color: "#32E0C4"
  },
});

从“React”导入React;
从“react native”导入{样式表、文本、视图、图像、尺寸、TouchableOpacity、ScrollView、SafeAreaView、Alert、ActivityIndicator、ImageBackground};
从“反应本机手势处理程序”导入{TextInput};
从“@react native community/async storage”导入异步存储;
从“@expo/vector icons”导入{Ionicons,FontAwesome}”;
从“expo字体”导入*作为字体;
从“react native raw bottom sheet”导入RBSheet;
从“力矩”中导入力矩;
从“react native WebView”导入{WebView};
从“react native render HTML”导入HTML;
从“@react native community/NetInfo”导入NetInfo;
从“反应数字格式”导入数字格式;
从“expo Crypto”导入*作为加密;
从“../../assets/utils/apirl”导入APIRL
从“../../assets/utils/AppData”导入AppData
const SLIDER_WIDTH=Dimensions.get('window').WIDTH;
常数项宽度=数学圆(滑块宽度*0.7);
常数项目高度=数学圆(项目宽度*3/4);
让自定义字体={
“Roboto”:需要(“../../assets/fonts/Roboto.ttf”),
“Titillium Web”:需要(“../../assets/fonts/TitilliumWeb.ttf”),
};
导出默认类PaymentStatus扩展React.Component{
建造师(道具){
超级(道具);
此.state={
秀:没错,
fontsLoaded:错,
加载:false,
票号长度:“,
id:“”,
idUser:“”,
dataEventTicket:[],
加载事件票证:false,
票务部分:[],
ticketArray:[],
点击次数:0
}
}
异步组件didmount(){
等待Font.loadAsync(customFonts);
const{navigation}=this.props
等待这一天({
idEvent:navigation.getParam(“idEvent”,”),
eventName:navigation.getParam(“eventName”,“”),
eventLocation:navigation.getParam(“eventLocation”,“”),
eventDate:navigation.getParam(“eventDate”,即“”),
eventTime:navigation.getParam(“eventTime”,即“”),
eventImg:navigation.getParam(“eventImg”,“”)
})
this.initAsync();
this.setState({fontLoaded:true})
}
异步组件willunmount(){
this.setState({loading:false})
}
initAsync=async()=>{
等待此消息。loadEventTicket()
};
异步加载事件票证(){
const id=“?id=“+this.state.idEvent
this.setState({loadingEventTicket:true})
等待获取(apirl.getCategoryPicket+id{
方法:“获取”,
标题:新标题({
“内容类型”:“应用程序/json”,
“Eventku Api密钥”:AppData.apiKey
})
})。然后(response=>response.json())。然后(responseJson=>{
试一试{
如果(响应状态){
常量数据=responseJson.result
这个.setState({
dataEventTicket:data.category,
})
for(var i=0;i{
console.log(错误);
警觉,警觉(“‘泰尔加迪·凯萨拉汉·帕达·阿皮卡西’)
})
this.setState({loadingEventTicket:false})
}
异步(buyTicket){
//this.props.navigation.navigate(“PaymentStatus”{
//id:item.id,
//eventName:item.event\u名称,
//eventAddress:item.event\u地址,
//eventDate:item.event\u日期,
//eventTime:item.event\u时间,
//orderID:item.order\u id,
//grandTotal:item.grandTotal,
//ImageUrl:item.image\u url
// });
这个.props.navigation.navigate(“TicketBuyerDetail”);
}
异步递增项(项){
var joined=this.state.ticketCart.concat(item.id);
这个.setState({
//ticketCart:已加入,
点击:this.state.clicks+1,
ticketCart:this.state.ticketCart+item.price,
});
console.log(this.state.ticketCart)
}
异步递减项(项){
如果(this.state.clicks!=0){
this.setState({clicks:this.state.clicks-1});
}
}
render(){
const dateFormat=矩(this.state.eventDate.format('D MMMM YYYY'))
const EventTicket=()=>(
(this.state.loadingEventTicket&&)||
{this.state.dataEventTicket.map((项,索引)=>(
{item.name}
{item.type==“已付”&&
{value}}/>
}
{item.type==“FREE”&&
免费的
}
{此.递减项(项)}>
{/*this.setState({clicks}}/>*/}
{this.state.clicks}
{this.incrementItem(item)}}>
))}
)
返回(
{this.state.eventName}
{this.state.eventLocation}
{dateFormat}
{this.state.eventTime}
小计
Rp.{this.state.ticketCart}
这是。_buyTicket()}>
贝利提克特
);
}
}
const styles=StyleSheet.create({
容器:{
背景颜色:“#fff”,
弹性:1
},
事件标题:{
},
事件图片背景:{
对准自己:“居中”,
身高:250,
宽度:尺寸。获取('窗口')。高度
},
事件