【问题标题】:React Native unable to resolve module from fileReact Native 无法从文件中解析模块
【发布时间】:2019-11-20 19:25:50
【问题描述】:

我正在尝试将所有 CSS 样式值存储到一个 ts 文件中:styles/base.ts,并将这些值导出到 styles/index.ts 文件中。
但是当我尝试在我的App.tsx 文件中使用从index.ts 导入值时,它说

无法从“App.tsx”解析模块“styles/index”:“styles/index” 在项目中找不到。`.

我不确定在应用程序中管理样式是否正确。谁能帮帮我?

这是我的base.ts 文件的样子:

export const colors = {
  grey: "#E3E1D6",
  black: "#333333",
};

index.ts:

import * as BaseStyle from "./base";
export {BaseStyle};

App.tsx:

import React from "react";
import {StyleSheet, View, Text} from "react-native";
import {BaseStyle} from "styles/index";
const App = () => {
  return (
    <>
      <View style={styles.body}>
        <Text>Test</Text>
      </View>
    </>
  );
};
const styles = StyleSheet.create({
  body: {
    backgroundColor: BaseStyle.colors.grey,
  },
});
export default App;

这是我的 package.json 的样子:

{
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.4"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "@types/jest": "^24.0.18",
    "@types/react-native": "^0.60.22",
    "@types/react-test-renderer": "16.9.0",
    "babel-jest": "^24.9.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0",
    "typescript": "^3.6.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    我认为这只是您导入时的拼写错误。 你应该写:

    import {BaseStyle} from "./styles/index";
    

    【讨论】:

      【解决方案2】:

      您可以使用此模式创建颜色类

      class Colors {
          static transparents = "#ffffff";
          static black = "#000";
      }
      export default Colors;
      

      你可以使用这条线导入颜色

      import Colors from './Colors';
      

      请按照以下步骤操作,这将对您有所帮助 它对我有帮助。

      【讨论】:

      • 嗨,你能告诉我使用 Class 而不是使用 const 有什么好处吗?
      • 通过创建一个类,您可以通过类名访问所有类变量。变量的名称。它提供对对象/变量的直接访问
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 2016-03-23
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      相关资源
      最近更新 更多