尝试在 React Native 中动态导入本地 SVG 时出现“无效调用”

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

我正在尝试使用React Native(v0.72.3)中的Suspense和lazy动态导入本地SVG文件。但我收到此错误:

ERROR  [Error: TransformError Utils/DynamicSvg.tsx: Utils/DynamicSvg.tsx:Invalid call at line 13: import(url)]
Error: Utils/DynamicSvg.tsx:Invalid call at line 13: import(url)
    at transformJS (/Users/me/projects/myproj/node_modules/metro-transform-worker/src/index.js:225:15)
    at transformJSWithBabel (/Users/me/projects/myproj/node_modules/metro-transform-worker/src/index.js:343:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.transform (/Users/me/projects/myproj/node_modules/metro-transform-worker/src/index.js:461:12)

这是我的代码:

import { Suspense, lazy } from 'react';
import { View } from 'react-native';

export const DynamicSvg = ({name}: any) => {
  
  console.log("name: " + name);
  const LazySvg = lazy(() => {
    const url = `./../assets/people/${name}`;
    
    return import(url);
  });

  return (
    <Suspense>
      <LazySvg />
    </Suspense>
  );
};

我在这里做错了什么以及如何解决它?

react-native svg import
1个回答
0
投票

React Native 不直接支持

SVG
语法或文件。因此,要解决此问题,您必须遵循安装指南:

  1. 安装
    react-native-svg
  2. 安装
    react-native-svg-transformer

然后在你的项目组件中,你可以像下面这样编写:

import { View } from 'react-native';
import YourSvgFile from './assets/svg/yourSvgFile.svg';

const TheComponent = () => {
  return (
    <View>
      <YourSvgFile />
    </View>
  );
};

它确实有效,如果你需要制作动态的,你应该使用

require
,请参阅以下内容:

import { Suspense, lazy } from 'react';
import { View } from 'react-native';

const DynamicSvg = ({ name }) => {
  const LazySvg = lazy(() => import(`../icons/${name}.svg`));

  return (
    <View>
      <LazySvg />
    </View>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.