通过变量动态导入文件-反应本机 [英] import file dynamically by variable - react native

查看:75
本文介绍了通过变量动态导入文件-反应本机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个path.json文件,其中包含组件的路径

I have a path.json file that contains the path of a component

// path.json

{
  "main": "./login/index.js",
  "paths": [
    {
      "name": "login",
      "path": "./login/index.js",
      "image": ""
    }
  ]
}

我想在react native中动态加载'./login/index.js'文件并呈现此特定文件

I want to load './login/index.js' file dynamically in react native and render this particular file

我当前的实现方式

const MyComponent = createLazyContainer(() => {
  const componentPath = PathJson.main; // ./login/index.js
  return import(`${componentPath}`); //import error here @ line 7
});

export default MyComponent;

我遇到以下错误:

第7行的无效调用:import(" + componentPath)

Invalid call at line 7: import("" + componentPath)

推荐答案

人们在线程中告诉您的内容是正确的,但我想添加一个可能的解决方案.所有的导入/需求都在编译时解决,而不是在您尝试执行的运行时解决.在运行应用程序时,如果尚未导入文件,则无法使用它们.

What people have been telling you in the thread is correct but I'd like to add one possible solution. All the imports/require are resolved at compilation time and not at running time which you are trying to do. By the time you are running your app, if you haven't imported the files, you can't use them.

有一种解决方法,假设您事先知道可能要执行工厂操作的所有文件:

There is a workaround tho, assuming that you know all the files that you might in advance which is to do something like a factory:

   const possiblePaths = {
     'one': require('path/to/file/1),
    'two': require('path/to/file/2)
}

funtion(type){
    return possiblePaths[type]
}

然后您以某种方式使用它:

And then you use it somehow like:

render(){
   const MyComponent = function('one')

  return <MyComponent/>
}

这或多或少是伪代码,我无法立即使用,但希望您能理解.您需要存储对可能需要的每个导入的引用,然后不要使用导入,请使用在编译时为您创建的引用.

This is more or less pseudo code and my not work right away, but hopefully yo get the idea. You need to store a reference to each of the imports you might need and then dont use the import, use the reference that was created for you at compilation time.

这篇关于通过变量动态导入文件-反应本机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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