未成功解构函数内的对象

Unsuccessfully destructuring the object inside the function

我在文件夹 utils

中有一个 js 文件名 index.js

文件内:

export const colors = {
  PRIMARY_COLOR: "#ff304f",
  SECONDARY_COLOR: "#002651",
  BORDER_COLOR: "#dbdbdb",
};

我尝试在我的 WeatherInfo 组件中解构它,如下所示:

import React from "react";
import { StyleSheet, View, Text, Image } from "react-native";

import { colors } from "../utils";

export default function WeatherInfo({ currentWeather }) {

  const { PRIMARY_COLOR } = colors;
  // console.log(colors);

  return (
    <View>
      <Text style={styles.textPrimary}>{temp}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  textPrimary: {
    fontSize: 40,
    color: PRIMARY_COLOR,
  },
});

我说 Can't find variable: PRIMARY_COLOR 时出错,但是如果我在函数内 console.log(colors),我可以看到在 expo 控制台中打印的对象。但是,如果我在函数之外执行它,它就可以工作。有人可以向我解释发生了什么吗?

你做得对,但你只是放错了代码,它应该在函数体之外,这样它才能在整个页面上可用

const { PRIMARY_COLOR } = colors;

将其上移一行。