【问题标题】:Getting error ''element type is invalid expected a string'' with component import in React Native在 React Native 中使用组件导入获取错误“元素类型无效预期字符串”
【发布时间】:2020-10-30 01:18:19
【问题描述】:

import Component from 'react'从“react”导入 React、{Component}?我得到这个错误 element type is invalid expected a string 如果我把这个 import import React, {Component} from 'react' 但如果我改成另一个就可以了.这样做有什么问题吗?谢谢你。我是编码新手。

【问题讨论】:

    标签: javascript firebase react-native


    【解决方案1】:
    import Component from 'react'
    

    相同
    import React from 'react'
    

    那是因为你正在导入 React 包的默认导出,你可以随意命名它。

    import React, { Component } from 'react'
    

    这个“组件”指的是 React.Component,你是从 'react' 导入“组件”加上默认导出。

    想象有一个名为exports.js 的具有多个导出的文件

    const DefaultExport = () => null
    
    export const OtherExport = () => null
    export const AnotherExport = () => null
    
    export default DefaultExport
    

    您可以使用

    导入您的组件
    import something from './exports' //this is DefaultExport
    import { OtherExport } from './exports' //OtherExport
    import { AnotherExport as RandomExport } from './exports' //AnotherExport
    import * as Exports from './exports' //you are importing all the exports
    

    对于最后一种情况import * as Exports from './exports',您可以访问和使用文件中的所有导出,例如

    Exports.default //refer to default export
    Exports.OtherExport //refer to OtherExport
    Exports.AnotherExport //refer to AnotherExport
    

    【讨论】:

      【解决方案2】:

      我要做的是:

      import React, {Component} from 'react';
      

      然后你可以在课堂上使用它:

      class Login extends Component
      

      {Component} 的使用只不过是在解构导入,

      如果你会这样做:

       import React, {Component} from 'react';
      

      那么你会像这样使用它:

      class Login extends React.Component
      

      这就是区别,希望对您有所帮助。

      请放心

      【讨论】:

        【解决方案3】:

        react默认不导出组件,需要解构导入

        【讨论】:

          猜你喜欢
          • 2018-05-30
          • 1970-01-01
          • 2021-03-13
          • 1970-01-01
          • 1970-01-01
          • 2020-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多