tem*_*ame 4 reactjs webpack webpack-dev-server
我已经设置了一个非常简单的React应用程序,我无法将任何组件导入到index.js.我的index.js,包含我的主<App />类的定义,工作正常,并以此行为例:
import { IntroductionPage } from './Components/IntroductionPage.js';
Run Code Online (Sandbox Code Playgroud)
使用从IntroductionPage.js导出的IntroductionPage组件的一个很好的定义,我得到的是关于在index.js中未定义的IntroductionPage的错误:
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `App`.
in App
Run Code Online (Sandbox Code Playgroud)
我不知道要改变什么 - 我可以看到来自IntroductionPage.js的console.log输出,所以它正在运行/编译.如果我将IntroductionPage组件定义移动到index.js,一切都很好.不知怎的,我在导入/导出步骤中丢失了它.
为什么会发生这种情况?
我想对有反应的导入和导出方案给出更多解释.
这是默认导入:
// App.js
import IntroductionPage from './IntroductionPage'
Run Code Online (Sandbox Code Playgroud)
它仅在IntroductionPage包含默认导出时才有效:
// IntroductionPage.js
export default 50
Run Code Online (Sandbox Code Playgroud)
在这种情况下,导入时为其分配的名称无关紧要:
// App.js
import IntroductionPage from './IntroductionPage'
import MySample from './IntroductionPage'
import Test from './IntroductionPage'
Run Code Online (Sandbox Code Playgroud)
因为它将始终解析为默认导出的任何内容IntroductionPage.
这是一个名为import的名为IntroductionPage:
import { IntroductionPage } from './IntroductionPage'
Run Code Online (Sandbox Code Playgroud)
它只能如果IntroductionPage包含一个名为export称为IntroductionPage:
export const IntroductionPage = 52
Run Code Online (Sandbox Code Playgroud)
在这种情况下,名称很重要,因为您通过其导出名称导入特定的东西:
// App.js
import { IntroductionPage } from './IntroductionPage'
import { mySample } from './IntroductionPage' // Doesn't work!
import { Test} from './IntroductionPage' // Doesn't work!
Run Code Online (Sandbox Code Playgroud)
要使这些工作,您可以将相应的命名导出添加到IntroductionPage:
// IntroductionPage.js
export const IntroductionPage = 50
export const mySample = 51
export const Test= 52
Run Code Online (Sandbox Code Playgroud)
一个模块只能有一个默认导出,但可以有多个命名导出(零,一个或多个).您可以将它们一起导入:
// App.js
import IntroductionPage, { mySample, Test } from './IntroductionPage'
Run Code Online (Sandbox Code Playgroud)
在这里,我们将默认导出导入为IntroductionPage,并将名为exports的名称分别命名为mySample和Test.
// IntroductionPage.js
export default 50
export const mySample= 51
export const Test= 52
Run Code Online (Sandbox Code Playgroud)
我们还可以在导入时为它们分配所有不同的名称:
// App.js
import X, { mySample as myTest, Test as myTest2} from './IntroductionPage'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
375 次 |
| 最近记录: |