如何使用React + ES6 + webpack导入和导出组件?
问题描述:
我正在玩 React
和 ES6
使用 babel
和 webpack
。我想在不同的文件中构建几个组件,在一个文件中导入,并将它们与 webpack
I'm playing around with React
and ES6
using babel
and webpack
. I want to build several components in different files, import in a single file and bundle them up with webpack
说我有几个这样的组件:
Let's say I have a few components like this:
my-navbar.jsx
my-navbar.jsx
import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';
export class MyNavbar extends React.Component {
render(){
return (
<Navbar className="navbar-dark" fluid>
...
</Navbar>
);
}
}
main-page.jsx
main-page.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import MyNavbar from './comp/my-navbar.jsx';
export class MyPage extends React.Component{
render(){
return(
<MyNavbar />
...
);
}
}
ReactDOM.render(
<MyPage />,
document.getElementById('container')
);
使用webpack并按照他们的教程,我有 main.js
Using webpack and following their tutorial, I have main.js
:
import MyPage from './main-page.jsx';
构建项目并运行后,我的浏览器控制台出现以下错误:
After building the project and running it, I get the following error in my browser console:
Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `MyPage`.
我做错了什么?如何正确导入和导出我的组件?
What am I doing wrong? How can I properly import and export my components?
答
尝试默认 :
import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';
export default class MyNavbar extends React.Component {
render(){
return (
<Navbar className="navbar-dark" fluid>
...
</Navbar>
);
}
}