Продолжайте получать «Не удается разрешить модуль» в react native

#javascript #android #react-native #expo

Вопрос:

Я совсем новичок в реагировании-родной. В настоящее время я пытаюсь добавить пользовательскую кнопку. Всякий раз, когда я пытаюсь импортировать созданный мной файл (или любой файл, созданный мной самим) Я продолжаю получать эту ошибку, которую не могу устранить. Я искал повсюду, но не нашел ни одного подходящего решения.

Соответствующая информация: Версия Npm: 6.14.13, версия React-Native: 0.63.2, Версия Expo: 4.5.2.

Структура проекта: https://imgur.com/a/zqtplbQ

Ошибка, которую я получаю:

 Unable to resolve module ./components/custombutton.js from C:UserslevikDesktopAppAppApp.js: 

None of these files exist:
  * componentscustombutton.js(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
  * componentscustombutton.jsindex(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
 

Код в App.js

 import 'react-native-gesture-handler';
import React from 'react';
import { StyleSheet, Text, View, Button, Alert, Dimensions } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import * as ScreenOrientation from 'expo-screen-orientation';
import { CustomButton } from "./components/custombutton.js";


const Stack = createStackNavigator();

export default function App() {
  ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT);
  return (
    <View  style={styles.container}>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name="Home"
            component={HomeScreen}
            options={{
              headerStyle: {
                backgroundColor: '#1e1e1e',
              },
              headerTintColor: '#fff',
            }}
          />
          <Stack.Screen 
            name="Thing"
            component={Thing}
            options={{
              headerStyle: {
                backgroundColor: '#1e1e1e',
              },
              headerTintColor: '#fff',
            }}
          />
          <Stack.Screen 
            name="About"
            component={About}
            options={{
              headerStyle: {
                backgroundColor: '#1e1e1e',
              },
              headerTintColor: '#fff',
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </View>
  );
}

const HomeScreen = ({ navigation }) => { //the homescreen
  navigation.addListener('focus', () => { //issue solver
    ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT);
  });
  return (
    <View style={styles.container}>
      <Button title="Poker" onPress={() => navigation.navigate('Thing')} />
      <Button title="About" onPress={() => navigation.navigate('About')} />
    </View>
    
  );
}

const Thing = ({ navigation }) => { //looks like i have to use expo's API for setting it to landscape mode
  ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE); //works
  return (
    <View style={styles.container}>
      <Button title="Home" onPress={() => navigation.navigate('Home')} />
      <Button title="About" onPress={() => navigation.navigate('About')} />
    </View>
    
  );
}

const About = ({ navigation }) => { //the 
  ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT); //works
  
  return (
    <View style={styles.container}>
      <Button title="Home" onPress={() => navigation.navigate('Home')} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1e1e1e',
  },
  title: {
    fontWeight: '700',
    fontSize: 40,
    color: 'white',
    paddingTop: 40,
    paddingLeft: 10,
  }
});

 

Код в custombutton.js:

 import React from 'react';
import { StyleSheet, Text, View, Button, Alert, Dimensions } from 'react-native';

export default function CustomButton() {
    return(
        <Text>this is text</Text>
    );
}
 

Вещи, которые я пробовал:

  1. Выньте пользовательскую кнопку из папки компоненты и измените строку импорта в App.js для обоих «./custombutton.js» и «./пользовательская кнопка»
  2. измените импорт на «./компоненты/пользовательская кнопка».
  3. Запустите как «expo start -c», так и «запуск npm —сброс кэша».

Комментарии:

1. Вам не нужно добавлять расширение .js в импорт и помещать структуру каталогов вашего кода.

Ответ №1:

Вы экспортируете CustomButton компонент как экспорт по умолчанию. Но при включении App.js вы импортируете его как именованный импорт. Итак, вам следует либо сделать:

export function CustomButton() на custombutton.js

или

import CustomButton from "./components/custombutton.js"; на App.js

Комментарии:

1. Я заберу назад свой предыдущий комментарий и благодарю вас, добрый сэр! Покопавшись в этом, я обнаружил, что проблема кроется в моей собственной глупости. Я приму этот ответ!

2. @therussianpp Добро пожаловать в StackOverflow! Вам не нужно добавлять «(РЕШЕНО)» к вашему вопросу, принятие ответа-это все, что вам нужно сделать 😉