简体   繁体   English

ReactJS从一个模块导出const和组件

[英]ReactJS export const and component from one module

I have two modules that I want to share a const array. 我有两个模块,我想共享一个const数组。 One of these modules includes both the const array and a component, whilst the other module only includes a component. 这些模块之一包括const阵列和组件,而另一个模块仅包括组件。

This is what I have in module "A". 这就是我在模块“A”中所拥有的。

export const ORDER_COLUMNS = [
  { name: 'orderNumber', title: 'Order', width: '10%',  type: 'string' },
  { name: 'orderType', title: 'Type', width: '10%',  type: 'string' }
];

class OrderGridControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        orderColumns: ORDER_COLUMNS
    };
  }
  ...

}

export default OrderGridControl;

And in module "B". 在模块“B”中。

import {OrderGridControl, ORDER_COLUMNS} from 'component/order-grid-control';

class OrderQueryPage extends React.Component {
      constructor(props) {
    super(props);
    this.state = {
        orderColumns: ORDER_COLUMNS
    };
    console.info(this.state.orderColumns);
  }

  ...

  render() {
    return (
      <div>
        <PropertyGrid gridSetup={this.state.orderColumns} />
      </div>
    );
  }
}

When I run this I get the following error. 当我运行这个时,我得到以下错误。 invariant.js:39 Uncaught 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 'moduleB'.

However, the console.info(this.state.orderColumns) line logs all the column objects I expect. 但是, console.info(this.state.orderColumns)行记录了我期望的所有列对象。

Interestingly, if I copy the array into module "B" and assign the columns in the constructor exactly the same way it seems to work. 有趣的是,如果我将数组复制到模块“B”并在构造函数中分配列完全相同的方式。 It only seems to be an issue when I'm importing from the other module. 当我从其他模块导入时,它似乎只是一个问题。

You've got it almost right-- you're exporting a default export ( OrderGridControl ) and a named export ( ORDER_COLUMNS ). 你几乎没有 - 你正在导出默认导出( OrderGridControl )和命名导出( ORDER_COLUMNS )。

However, in B.js, you're trying to import two named exports. 但是,在B.js中,您尝试导入两个命名导出。

Modify your import to look like this: 将导入修改为如下所示:

import OrderGridControl, { ORDER_COLUMNS } from 'component/order-grid-control';

The advantage of having a default export is that you don't have to match its name exactly when importing it, so you could do something like 具有默认导出的优点是,在导入时不必完全匹配其名称,因此您可以执行类似的操作

import GridControl, { ORDER_COLUMNS } from 'component/order-grid-control';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM