You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中SVG组件设置height/width报TypeScript错误求助

React Native SVG组件设置height/width时出现TypeScript类型错误
import {StyleSheet, Text, View} from 'react-native';
import React from 'react';

import Phone from '../assets/images/icons/phone.svg';
const Background = () => {
  return (
    <View>
      <Text>Background</Text>
      <View>
        <Phone height={400} width={300} />
      </View>
    </View>
  );
};

运行时出现TypeScript错误:
error : Type '{ height: number; width: number; }' is not assignable to type 'IntrinsicAttributes'.
Property 'height' does not exist on type 'IntrinsicAttributes'.

已按教程完成安装步骤,但设置SVG组件的height和width属性仍报错,解决方案如下:

  • 安装SVG类型定义包
    执行命令安装react-native-svg对应的TypeScript类型依赖:

    npm install @types/react-native-svg --save-dev
    # 或使用yarn
    yarn add @types/react-native-svg --dev
    
  • 添加SVG类型声明文件
    在项目根目录或src文件夹下创建svg.d.ts文件,写入以下内容:

    declare module "*.svg" {
      import React from 'react';
      import { SvgProps } from "react-native-svg";
      const content: React.FC<SvgProps>;
      export default content;
    }
    
  • 配置tsconfig.json
    确保tsconfig.json的include数组包含这个声明文件,示例:

    {
      "include": [
        "src/**/*",
        "svg.d.ts"
      ]
    }
    
  • 重启TypeScript服务
    修改类型声明后,重启编辑器或TypeScript语言服务,让新的类型定义生效。

完成以上步骤后,导入的SVG组件会自动拥有SvgProps的所有属性(包括height、width),TypeScript错误即可解决。

内容的提问来源于stack exchange,提问作者Siddhant Shelake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:40:25