为什么我不能将const变量转移到不同的React文件中

e4yzc0pl  于 2023-08-07  发布在  React
关注(0)|答案(1)|浏览(135)

因此,我试图将const变量从一个文件转移到另一个文件。由于某种原因,我无法访问它,它也不允许我在文本文件中显示它下面是homepage.js代码和pay.js文件。我试图将displayedAmount变量从主页文件转移到支付文件,然后将其显示在文本元素中。但是当我这样做时,我得到这个错误“错误:文本字符串必须在组件内呈现。”

  1. import { StyleSheet, Text, View, Image, Dimensions, TouchableOpacity, Alert, Animated } from 'react-native';
  2. import { FontAwesome5 } from '@expo/vector-icons';
  3. import React, { useState, useEffect, useRef } from 'react';
  4. import { useNavigation } from '@react-navigation/native';
  5. import pay from './pay';
  6. const homepage = ({ route, navigation }) => {
  7. const [selectedAmount, setSelectedAmount] = useState("0");
  8. const [displayedAmount, setDisplayedAmount] = useState("0");
  9. const fadeAnim = new Animated.Value(0); // initial opacity
  10. const screenWidth = Dimensions.get('window').width;
  11. const buttonWidth = screenWidth * 0.45;
  12. const spaceBetweenNumbers = 100;
  13. useEffect(() => {
  14. Animated.timing(
  15. fadeAnim,
  16. {
  17. toValue: 1,
  18. duration: 1000,
  19. useNativeDriver: true,
  20. }
  21. ).start();
  22. if (selectedAmount.includes('.')) {
  23. const [whole, decimal] = selectedAmount.split('.');
  24. setDisplayedAmount(`${isNaN(parseInt(whole)) ? "0" : parseInt(whole).toLocaleString()}.${decimal}`);
  25. } else {
  26. setDisplayedAmount(isNaN(parseInt(selectedAmount)) ? "0" : parseInt(selectedAmount).toLocaleString());
  27. }
  28. Animated.timing(
  29. fadeAnim,
  30. {
  31. toValue: 0,
  32. duration: 1000,
  33. useNativeDriver: true,
  34. }
  35. ).start();
  36. }, [selectedAmount]);
  37. const handleNumberPress = (number) => {
  38. if (selectedAmount.length < 5) {
  39. setSelectedAmount(prevState => prevState === "0" ? String(number) : prevState + number);
  40. }
  41. };
  42. const handleDecimalPress = () => {
  43. if (!selectedAmount.includes(".") && selectedAmount.length < 4) {
  44. setSelectedAmount(prevState => prevState + ".");
  45. }
  46. };
  47. const handleDeletePress = () => {
  48. setSelectedAmount(prevState => prevState.slice(0, -1) || "0");
  49. };
  50. const goTopay = () => {
  51. navigation.navigate('Pay', { displayedAmount }); // passing displayedAmount as a parameter
  52. };

个字符

wd2eg0qa

wd2eg0qa1#

两个选项:
1.对于静态值,导出非嵌套const中的值。通常,将常量分开,以便在两个组件需要相同常量但其中一个组件需要另一个组件时不会创建required循环。仅供参考导出常量命名为导出与默认导出。所以需要用大括号导入。

  1. //constants file
  2. export const value1 = '123456'
  3. // component file
  4. import { value1 } from '../constants'

字符串
1.对于需要跨应用导出的有状态值,请查看React.Context API或全局状态管理库。
1.对于子组件,您可以通过props将数据传递给组件。
1.对于react-navigation屏幕导航,您可以通过params对象将参数发送到屏幕。

相关问题