我正在玩React和ES6使用babel和webpack。我想在不同的文件中构建几个组件,导入在一个文件,并捆绑起来与webpack
让我们说,我有这样的几个组件:
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
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:
import MyPage from './main-page.jsx';
在构建项目并运行它后,我在浏览器控制台中收到以下错误:
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`.
我究竟做错了什么?如何正确导入和导出我的组件?
尝试默认您的组件中的导出:
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> ); } }