谁能向我解释为什么
import { React } from 'react';
打破一切,但
import React from 'react';
工作正常吗?他们说的不是同一件事吗?我试图在文档和互联网的其他地方找到答案,但我无法弄清楚。我觉得可能跟 Babel 有关系吧?
如果有帮助,这是我的 npm 包:
"dependencies": {
"moment": "^2.18.1",
"prop-types": "^15.5.10",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router-dom": "^4.0.0",
"styled-jsx": "^3.2.1",
"uuid": "^3.2.1"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"eslint": "^4.13.1",
"eslint-loader": "^1.9.0",
"eslint-plugin-react": "^7.5.1",
"file-loader": "^1.1.6",
"html-webpack-plugin": "^2.29.0",
"react-hot-loader": "^3.0.0-beta.7",
"url-loader": "^0.6.2",
"webpack": "^3.4.0",
"webpack-dev-server": "^2.5.0"
}
Run Code Online (Sandbox Code Playgroud)
import React from 'react'这实质上是说“从模块中找到默认导出react并将其导入为我想要调用的常量React。”
import { React } from 'react'这表示“从react显式命名的模块中找到导出React,并将其作为我想要调用的常量导入这里React。”
import { React } from 'react'?Because there isn't an export named React in the react package. There is only a single default export. If you do this, you'll find that React is undefined.
React in my code. So, couldn't I just name it anything I want, like import Foobar from 'react'?No, sorry. You need to import the default and name it React. This is because anytime you write JSX code like <MyComponent /> or <App />, this JSX code is transpiled and uses React.createElement(). So, you need to have access to React.
Helpful references:
区别在于默认导出和命名导出之间。
class React {
render() {
// some code...
}
}
export default React;
Run Code Online (Sandbox Code Playgroud)
您可以react.js在项目中导入上述文件,例如
import React from "./react.js";
Run Code Online (Sandbox Code Playgroud)
export class React {
render() {
// some code...
}
}
export const Component = () => {
// some code...
};
Run Code Online (Sandbox Code Playgroud)
然后你必须react.js在你的项目中导入上面的文件
import { React, Component } from "./react.js";
Run Code Online (Sandbox Code Playgroud)
TL;DR - 从这里了解默认导出和命名导出
| 归档时间: |
|
| 查看次数: |
10907 次 |
| 最近记录: |