【问题标题】:React Native, can't import custom componentsReact Native,无法导入自定义组件
【发布时间】:2019-02-25 03:55:14
【问题描述】:

我是 React Native 的新手,我目前正在尝试创建一个名为 OpButton 的自定义组件。它只是一个按钮,以便我可以尝试导入和导出组件。但是,每次我尝试导入它时,我都会不断收到诸如“Imvariant Violation”之类的错误,我不知道如何修复它。

import React, { Component } from 'react';
import { Button, Alert } from 'react-native';
export default class OpButton extends Component {
  render() {
    return (
      <Button
       onPress={() => Alert.alert("Hello World")}
       title= "Hello World"
       color="#841584"
       accessibilityLabel="Learn more about this purple button"
      />
   );
 }
}

我的按钮.js

import React, { Component } from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import { OpButton } from "./src/components/button";
 export default class App extends Component {
  render() {
   return (
    <OpButton></OpButton>
  );
 }
}

我的 App.js

【问题讨论】:

标签: react-native


【解决方案1】:

试试import OpButton from "./src/components/button"

当您要从中导入的文件将变量导出为 const (export const OpButton . . .) 时,导入时会使用花括号,但当您使用 export default OpButton 时,当您从没有花括号的文件中导入时,您总是导入默认的东西,无论你在导入中如何称呼它。所以你可以做import AnyNameYouWant from "./src/components/button",然后在你的App.js中使用&lt;AnyNameYouWant /&gt;

【讨论】:

    【解决方案2】:

    虽然答案已经被接受。我想让你清楚一些事情。这里需要了解两点

    1. 导出默认类
    2. 导出类

    当您使用导出默认类时,这意味着默认情况下会导出组件,您可以像下面这样导入

      import component from ‘./Component’;
    

    当你使用没有默认的导出类时,你可以像下面这样导入

      import {component, component1} from ‘./Component’;
    

    【讨论】:

    • React Native 中没有 div 或 span
    • 对不起,我在 React-native 中没有什么。感谢您指出
    猜你喜欢
    • 2020-11-04
    • 2019-06-21
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多