![](/img/trans.png)
[英]Can I pass a 'const' variable from one component to another in ReactJS?
[英]ReactJS export const and component from one module
我有兩個模塊,我想共享一個const數組。 這些模塊之一包括const陣列和組件,而另一個模塊僅包括組件。
這就是我在模塊“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;
在模塊“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>
);
}
}
當我運行這個時,我得到以下錯誤。 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'.
但是, console.info(this.state.orderColumns)
行記錄了我期望的所有列對象。
有趣的是,如果我將數組復制到模塊“B”並在構造函數中分配列完全相同的方式。 當我從其他模塊導入時,它似乎只是一個問題。
你幾乎沒有 - 你正在導出默認導出( OrderGridControl
)和命名導出( ORDER_COLUMNS
)。
但是,在B.js中,您嘗試導入兩個命名導出。
將導入修改為如下所示:
import OrderGridControl, { ORDER_COLUMNS } from 'component/order-grid-control';
具有默認導出的優點是,在導入時不必完全匹配其名稱,因此您可以執行類似的操作
import GridControl, { ORDER_COLUMNS } from 'component/order-grid-control';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.