【问题标题】:re-export es6 class module not working if use as class extender如果用作类扩展器,则重新导出 es6 类模块不起作用
【发布时间】:2018-12-06 08:46:07
【问题描述】:

我有 5 个 js 文件,

我从bar.js 导出了一个名为NewComponent 的新组件 然后在route.js我用同名NewComponent重新导出, 在other.js NewComponent 上工作正常, 但在dummy.js NewComponent 中没有定义, 而如果直接从bar.js导入NewComponent可以正常运行(见sample.js), 是我做错了吗?

/* bar.js */
import { Component } from 'react'
export default class NewComponent extends Component { }


/* route.js */
export { default as NewComponent } from './bar'

/* other.js */
import { NewComponent } from './route'
export default class Other extends Component {
  render() {
    return (
      <NewComponent /> /* work */
    )
  }
}

/* dummy.js */
import { NewComponent } from './route'
export default class Dummy extends NewComponent { } /* undefined is not an object (evaluating '_bar.default') */


/* sample.js */
import NewComponent from './bar'
export default class Sample extends NewComponent { } /* work */

【问题讨论】:

  • 只需阅读 Dan Abramov stackoverflow.com/a/36796281/1826429 的这个答案(导入时何时使用花括号)
  • 谢谢@goldy,我已经阅读了你给我的参考资料,我认为我没有对 Dan-Abramov 描述的规则犯错误,我需要 route.js 来导出我的所有文件,并且我在route.js上使用的导出方法没有问题,只有当该类被另一个类扩展时才会出现错误

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

你需要像这样导入(不用花括号{...}

/* dummy.js */
import NewComponent from './route'; // this is import Other component

other.js 中看到您将Other 作为默认组件导出并在Other 中使用NewComponent 组件,而不是像在route.js 中那样导出它


在此处阅读有关默认导入与命名导入的更多信息https://medium.com/@etherealm/named-export-vs-default-export-in-es6-affb483a0910

【讨论】:

  • 感谢您的回答@abdullah,但错误仍然不会消失,现在如果我使用您正在使用的方法我找不到NewComponent变量,因为在route.js上没有导出默认
  • 我需要route.js来重新导出我所有的文件,并且我在route.js上使用的导出方法没有问题,只有当类被另一个类扩展时才会出现错误跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多