简体   繁体   English

函数内的对象解构失败

[英]Unsuccessfully destructuring the object inside the function

I have a js file name index.js inside a folder utils我在文件夹utils有一个 js 文件名index.js

Inside the file:文件内部:

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

I try to destructuring it inside my WeatherInfo component like this:我尝试在我的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,
  },
});

I got error of saying Can't find variable: PRIMARY_COLOR , however if I console.log(colors) inside the function, I can see the object printed in the expo console.我收到错误说Can't find variable: PRIMARY_COLOR ,但是如果我在函数内部console.log(colors) ,我可以看到在博览会控制台中打印的对象。 However, if I do it outside the function, it works.但是,如果我在函数之外执行此操作,则它会起作用。 Can someone explain to me what happened?有人可以向我解释发生了什么吗?

You are doing it right, but you just misplaced your code it should be outside from function body that's how it will be available on the whole page你做得对,但你只是把你的代码放错了地方,它应该在函数体之外,这就是它在整个页面上可用的方式

const { PRIMARY_COLOR } = colors;

Move it up just one line.将它向上移动一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM