首页 > 解决方案 > 无法在 react native 中导入 .js 文件

问题描述

截屏

我正在尝试从组件文件夹中导入这三个组件,但它不允许我这样做。导入语句显示为灰色并且不读取我的 .js 文件。我根本不认为它是我的文件路径,因为我能够以相同的方式从资产文件夹导入图像。任何帮助,将不胜感激!

应用程序.js

import { StatusBar } from "expo-status-bar";
import React, { useState } from "react";
import { Button, ImageBackground, SafeAreaView, StyleSheet, Text, TouchableWithoutFeedback, View } from "react-native";

import header from "./components/header";
import item from "./components/items";
import add from "./components/add";

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <ImageBackground source={require("./assets/cart.jpg")} style={styles.image}></ImageBackground>
      <StatusBar style="auto" />

      <Text style={styles.title}> Smart Shopper </Text>
      <Button title="Create A Shopping List" style={styles.button} />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    fontSize: 50,
    fontFamily: "Roboto",
    fontWeight: "100",
    color: "black",
    bottom: 250,
  },
  image: {
    width: "100%",
    height: "100%",
    position: "absolute",
  },
});

header.js

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

export default function header() {
  return (
    <View style={styles.header}>
      <Text style={styles.title}>My Todos</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  header: {
    height: 80,
    paddingTop: 38,
    backgroundColor: "coral",
  },
  title: {
    textAlign: "center",
    color: "#fff",
    fontSize: 20,
    fontWeight: "bold",
  },
});

标签: javascriptreactjsreact-native

解决方案


这实际上不是一个错误。这显示为灰色,因为 VS 格式化程序无法识别它是一个反应组件,因为您在组件名称中使用了所有小写字母。你的反应组件应该在 CamelCase 中。建议大家在 react 组件中使用 Camel Case 名称。

因此,首先以驼峰形式更改所有组件名称和文件名,如下所示:

更改文件名Header.js

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

export default function Header() {
  return (
    <View style={styles.header}>
      <Text style={styles.title}>My Todos</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  header: {
    height: 80,
    paddingTop: 38,
    backgroundColor: "coral",
  },
  title: {
    textAlign: "center",
    color: "#fff",
    fontSize: 20,
    fontWeight: "bold",
  },
});

对所有组件执行此操作。

现在,像这样在你的 app.js 中导入它:

import Header from "./components/Header";
import Item from "./components/Items";
import Add from "./components/Add";

推荐阅读