【问题标题】:why I have to export const?为什么我必须导出常量?
【发布时间】:2019-10-10 09:56:21
【问题描述】:

我是 React 和 ES6 的新手,仍在努力理解它的语法,下面是我书中的示例代码:

import React from 'react';

export const App = () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

export default App;

但为什么我也必须使用“const”,为什么我不能这样做;

export default App = () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

它编译但导致运行时错误,我不知道为什么,我总是可以在没有任何错误的情况下执行以下操作:

export default function (…) { … } 

我真的很困惑

【问题讨论】:

  • 可以使用export default,但未命名默认导出,因此您必须删除App = 部分
  • @CertainPerformance 但是export default App; 呢,不是也有名字吗?

标签: javascript reactjs


【解决方案1】:

命名默认导出没有意义,因为当您导入它时,您可以将其作为任何东西导入

export default () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

// can be imported as
import Foo from './App';
import Bar from './App';
import AnythingYouCanThinkOf from './App';

如果你想命名导入:

export const App = () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

// can be imported only as
import { App } from './App';

另外请注意,一个文件中可以有多个命名导出,但只有一个默认导出。

export default () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>
export const Header = () => <div>Header</div>
export const Footer = () => <div>Footer</div>
export const Sidebar = () => <div>Sidebar</div>

// imports
import AnyNameYouWantWhichIsDefaultExport, { Header, Footer, Sidebar } from './App'

【讨论】:

  • 那么为什么使用 const,我可以进行命名导入?
  • 因为它是它的工作方式,所以是您的导出名称。不必使用 const,也可以 export function Header() { } for named export。
【解决方案2】:

当你要导出一个 default 值时,你想在其他地方不带名称地导入它(当你在其他地方导入它时准确地命名它)然后你不能只是 export默认 它带有名称,因此要导出默认值,您可以执行以下操作:

// Just export it
export default () => ...

// Or this way
const App = () => ...

export default App;

【讨论】:

    【解决方案3】:

    您可以只导出default,但默认导出不会在导入时强制使用名称。因此,代码如下所示:

    export default () => <h1 className="bg-primary text-white text-center p-2">
      Hello Adam
    </h1>
    

    【讨论】:

    • 但是示例中的export default App; 不也是这样命名的吗?
    • 不,App 指的是函数。所以,它没有被命名。您不导入基于名称的默认导出:import App from './App';。导入中的名称 App 可以是任何名称:import Anything from './App';
    • @secondimage after export default 需要是一个值。 = 使其声明无效
    • 是的,但您可以按名称导入它:import {default as sth} from "./somewere.js"。它有一个名字。
    • @secondimage 你可能会感兴趣的一点:如果你把App = () =&gt; {...} 放在括号中,它就会有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2013-11-09
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多