使用动态路径react-native异步导入

问题描述 投票:0回答:1

在网络中,我可以使用带有动态路径的异步导入。在react-native中出现错误

export function App() {
  const load = async (path: string) => {
    // I have success - {"test": [Function test]}
    const res = await import('./theme/test');

    // I have error - Invalid call at line 30: import(`./theme/${path}`)]
    const res2 = await import(`./theme/${path}`);
  };

  useEffect(() => {
    load('test');
  }, []);

  return <Text>test</Text>;
}

如何在react-native中使用带有动态路径的异步导入?也许需要在 Metro.config.js 上进行特殊设置

MDN 中描述了类似的情况

react-native metro-bundler
1个回答
0
投票
export function App() {
  const moduleMap = {
    test: require('./theme/test'),
    // Add more mappings as needed
  };

  const load = async (path: string) => {
    const modulePath = moduleMap[path];
    if (!modulePath) {
      // Handle case when path is not found in moduleMap
      return;
    }
    const res = await modulePath;
    console.log(res);
  };

  useEffect(() => {
    load('test');
  }, []);

  return <Text>test</Text>;
}

嗨施佩隆。请尝试此代码并使用 require 而不是 import。

© www.soinside.com 2019 - 2024. All rights reserved.