从父目录反应导入 [英] React import from parent directory
问题描述
我无法从项目目录的父目录导入文件.为了让事情尽可能简单,我在父目录中创建了新的 react-native 项目和文件test.js".我尝试使用以下代码导入它:
I am unable to import file from parent of project directory. To make things as simple as possible, I created new react-native project and file 'test.js' in a parent directory. I tried to import it with this code:
var Test = require('../test.js');
和
import Test from ('../test.js');
这些都不起作用 - 在 xcode 中运行时出现以下错误:
None of these worked - when run in xcode I have following error:
未捕获的错误错误:UnableToResolveError:无法解析模块../test.js 来自/Users/UserName/Downloads/TestReact/index.ios.js:无效目录/Users/UserName/Downloads/test.js
uncaught error Error: UnableToResolveError: Unable to resolve module ../test.js from /Users/UserName/Downloads/TestReact/index.ios.js: Invalid directory /Users/UserName/Downloads/test.js
是否可以使用 react-native 从父目录导入文件?I̶̶k̶n̶o̶w̶̶i̶t̶̶w̶o̶r̶k̶s̶̶w̶i̶t̶h̶̶r̶e̶a̶c̶t̶J̶S̶.
Is it possible to import file from parent directory with react-native? I̶ ̶k̶n̶o̶w̶ ̶i̶t̶ ̶w̶o̶r̶k̶s̶ ̶w̶i̶t̶h̶ ̶r̶e̶a̶c̶t̶J̶S̶.
问候
编辑 - 添加代码
test.js
'use strict';
import React, {Component,View,Text} from 'react-native';
class Test extends Component{
render(){
return (
<View>
<Text>
SAMPLE TEXT
</Text>
</View>
);
}
}
module.exports = Test;
index.ios.js
index.ios.js
'use strict';
import React, {AppRegistry, View} from 'react-native';
import Test from '../test.js';
var TestReact = React.createClass({
render: function() {
return (
<View><Test/></View>
);
}
});
AppRegistry.registerComponent('TestReact', () => TestReact);
edit - 添加文件层次结构:截图
edit - added files hierarchy: screenshot
编辑 - 实际上我错了,网络反应也不可能.当我尝试构建时出现以下错误:
edit - actually I was wrong, it's impossible with web react too. When I try to build I got following error:
模块解析失败:/path_to_file/aaa1.js 第 1 行:意外的令牌您可能需要一个合适的加载器来处理这个文件类型.
Module parse failed: /path_to_file/aaa1.js Line 1: Unexpected token You may need an appropriate loader to handle this file type.
所以在问题中添加反应标签.
So adding react tag to the question.
推荐答案
试试这个 ./../Component.js
.这个对我有用.如果您需要访问相邻目录中的组件 ./../AdjDir/Component.js
Try this ./../Component.js
. It works for me.
More over if you need access a component from adjacent directory ./../AdjDir/Component.js
这篇关于从父目录反应导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!