我认为我出了点问题,我不断收到错误消息“ this.deliveryFareEstimate()未定义”
我试图总结从一个道具中获得的价值,但是它不能按计划工作,我认为这样做做错了。我对编程总体来说是新手。
下面是我用来实现它的示例代码。
import React, { Component } from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity, SafeAreaView, StatusBar } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import RNSlidingButton, { SlideDirection } from "../../components/RNSlidingButton";
import { Block } from "../../components";
const PerKm = 55;
const PerKg = 35;
export default class ConfirmBooking extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { handleBackPress, estimatedWeight, deliveryDuration } = this.props;
FareEstimate = () => {
const totalDistanceCost = PerKm * deliveryDuration;
const totalParcelWeight = PerKg * estimatedWeight;
const estimatedFare = totalParcelWeight + totalDistanceCost;
return estimatedFare;
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
{/* Delivery Details */}
<View style={styles.header}>
<TouchableOpacity
onPress={handleBackPress}
style={styles.navBarButton}
>
<Ionicons name="md-arrow-back" size={23} color="#FFF" />
</TouchableOpacity>
<Text style={styles.headerText}> Details</Text>
</View>
{/* content holder */}
<View style={styles.content}>
<Block style={styles.generalBlock}>
<Text style={styles.generalBlockHeaderText}>
ETA from Pick up
</Text>
<Text style={styles.generalBlockText}>
{deliveryDuration} Mins
</Text>
</Block>
<Block style={styles.generalBlock}>
<Text style={styles.generalBlockHeaderText}>
Estimated Parcel Weight
</Text>
<Text style={styles.generalBlockText}>{estimatedWeight} Kg</Text>
</Block>
<View style={styles.fareAndConfirm}>
<Text style={styles.fareAndConfirmHeaderText}>Fare</Text>
<Text style={styles.fareAndConfirmText}>
${this.FareEstimate()}
</Text>
</View>
</View>
</View>
</SafeAreaView>
);
}
}
最佳答案
FareEstimate
定义不正确。始终使用const
或let
定义局部变量。
const FareEstimate = () => {
const totalDistanceCost = PerKm * deliveryDuration;
const totalParcelWeight = PerKg * estimatedWeight;
const estimatedFare = totalParcelWeight + totalDistanceCost;
return estimatedFare;
};
由于FareEstimate是在
render()
内部本地定义的,因此无需this
即可调用它<Text style={styles.fareAndConfirmText}>${FareEstimate()}</Text>