javascript ReactJS - 无法导入组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33523736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReactJS - Can't import component
提问by Luca Mormile
I'm brand new to ReactJS. I'm developing a little single page app and I'm just trying to create my components to import within my main component.
我是 ReactJS 的新手。我正在开发一个小的单页应用程序,我只是想创建我的组件以在我的主要组件中导入。
TestComponent.jsx
测试组件.jsx
import React from 'react'
export class TestComponent extends React.Component {
render() {
return (
<div className="content">Test Component</div>
)
}
}
Inside my main.jsxI've imported this component calling
在我的main.jsx 中,我导入了这个组件调用
import TestComponent from './components/TestComponent.jsx'
Then I've tried to call my component for a specific route:
然后我尝试为特定路线调用我的组件:
render(
(<Router history={history}>
<Route path="/" component={NavMenu}>
<IndexRoute component={Index}/>
<Route path="test" component={TestComponent}></Route>
</Route>
</Router>),
document.getElementById('main')
)
I've not got any errors from the console, but I don't see my component. What am I doing wrong?
我没有从控制台收到任何错误,但我没有看到我的组件。我究竟做错了什么?
回答by Mad Scientist
The import syntax without curly braces is for importing default exports, not for importing named exports.
没有花括号的导入语法用于导入默认导出,而不是用于导入命名导出。
Make your component the default export:
使您的组件成为默认导出:
TestComponent.jsx
测试组件.jsx
import React from 'react'
export default class TestComponent extends React.Component {
render() {
return (
<div className="content">Test Component</div>
)
}
}
Alternatively you should be able to import it as it is with the following import statement:
或者,您应该可以使用以下导入语句按原样导入它:
import { TestComponent } from './components/TestComponent.jsx'
You might want to read up on ES6 modules (e.g. in Exploring ES6) if you want to use ES6 in your React code.
如果你想在你的 React 代码中使用 ES6,你可能需要阅读 ES6 模块(例如在探索 ES6 中)。
回答by sao
Make sure to include semicolons after the import statements too. you might get away with a browser (or environment like Node) reading the code in some cases, but the import function runs right into your export in this code.
确保在导入语句之后也包含分号。在某些情况下,您可能会使用浏览器(或 Node 之类的环境)读取代码,但导入功能会在此代码中直接运行到您的导出中。