我正在尝试在 React Native 中组织我的通用 theme
文件夹。但在尝试默认导出不同文件中的模块时发现了问题。基本上,尝试做这个基本结构:
+-- components
+-- theme
| +-- appStyles.js
| +-- colors.js
| +-- index.js
在theme/appStyles.js
中将导出默认的单个对象(与colors.js
相同):
export default {
screen: {
flex: 1,
},
};
在theme/index.js
中看起来像这样,它将导出默认的对象,映射主题文件夹中的文件:
import AppStyles from './appStyles';
import Colors from './colors';
export default {
AppStyles,
Colors,
};
当我尝试在另一个模块(即 SomeComponent.js
)中使用它时,它只是未定义并且无法使用:
import { AppStyles } from '../theme';
console.log(AppStyles); // would log 'undefined'
<小时/>
作为一种解决方法,我一直在做:
在theme/appStyles.js
中:
export const AppStyles = {
screen: {
flex: 1,
},
};
在theme/index.js
中:
export * from './appStyles';
然后它就可以在 SomeComponent.js
中使用:
import { AppStyles } from '../theme';
console.log(AppStyles); // would log Object structure
<小时/>
一直在 ReactJS Web 中使用这种“模式”。只是想知道 React Native 如何处理这个模块解析。
最佳答案
无需通过 {}
包装默认导出
import AppStyles from './appStyles';
export default AppStyles;
而不是简单地使用您想要的任何名称导入
import AppStyles from '../theme';
console.log(AppStyles);
我有多个内容要从索引导出
import AppStyles from '../theme';
import Color from '../color';
export{
Appstyle as default,
Color
}
而不是简单地导入为
import AppStyles, {Color} from '../theme';
console.log(AppStyles);
console.log(Color);
关于javascript - 如何修复导入过程中的 'TypeError: undefined is not an object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753063/