如何使用 React + ES6 + webpack 导入和导出组件? [英] How to import and export components using React + ES6 + webpack?

查看:25
本文介绍了如何使用 React + ES6 + webpack 导入和导出组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 babelwebpackReactES6.我想在不同的文件中构建几个组件,导入单个文件并将它们与 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:

我的导航栏.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?

推荐答案

尝试默认在您的组件中设置导出:

Try defaulting the exports in your 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>
      );
    }
}

通过使用默认值,您表示将成为该模块中的成员,如果没有提供特定的成员名称,则该模块将被导入.您还可以通过以下方式表达您想要导入名为 MyNavbar 的特定成员: import {MyNavbar} from './comp/my-navbar.jsx';在这种情况下,不需要默认值

by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed

这篇关于如何使用 React + ES6 + webpack 导入和导出组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆