为什么我必须导出const?

时间:2019-10-10 09:56:21

标签: javascript reactjs

我是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 (…) { … } 

我真的很困惑

3 个答案:

答案 0 :(得分:2)

命名默认导出没有意义,因为导入时可以将其导入为任何内容

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'

答案 1 :(得分:0)

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

default

答案 2 :(得分:0)

当您要导出默认值时,要在没有其他名称的情况下将其导入而无需命名(在其他位置导入时准确命名),那么您就不能仅导出默认值并添加名称,以便导出默认值,您可以执行以下操作:

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

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

export default App;
相关问题