将道具传递给 svg 组件时,react-native-web 打字稿错误

时间:2020-12-28 14:45:42

标签: reactjs typescript react-native svg react-native-web

我已经配置了 Metro 和 webpack 来像这样导入 svgs:

import PlayIcon from '../../assets/icons/play-icon.svg';

...

return () => <PlayIcon />

问题是当我尝试传递 props 时,我的编辑器 (vscode) 和 webpack 终端上都出现打字稿错误:

Type '{ width: number; height: number; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'width' does not exist on type 'IntrinsicAttributes'

这是我的tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "lib": [
      "es6"
    ],
    "allowJs": true,
    "jsx": "react",
    "noEmit": true,
    "isolatedModules": true,
    "strict": false,
    "moduleResolution": "node",
    "baseUrl": "./",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ],
  "include": [
    "src",
    "src/types/definitions/svg.d.ts"
  ]
}

src/types/definitions/svg.d.ts

declare module '*.svg' {
    import { SvgProps } from 'react-native-svg';
    const content: React.FC<SvgProps>;
    export default content;
}

// also tried, amongst others
declare module '*.svg' {
    const content: any;
    export default content;
}

我尝试过的事情:

  1. 将“**/*.svg”传递给 tsconfig.json.exclude
  2. 声明 svg 模块定义的不同方法。我在此处发布的内容是我在许多教程和参考资料中找到的内容。

那我做错了什么?

1 个答案:

答案 0 :(得分:1)

对我有用的是添加文件 src/declarations.d.ts

declare module '*.svg' {
    import React from 'react';
    import { SvgProps } from 'react-native-svg';
    const content: React.FC<SvgProps>;
    export default content;
}