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

升级react-native-svg至13.4.0后fill属性类型转换错误如何解决?

React Native Expo SDK48 react-native-svg@13.4.0 fill 属性类型转换错误解决方案

问题背景

使用Expo SDK48(要求react-native-svg@13.4.0)开发应用,升级react-native-svg至13.4.0后,使用fill属性时触发以下错误:

Error while updating property 'fill' of a view managed by: RNSVGPath
null
java.lang.Double cannot be cast to java.lang.String

项目核心依赖:

{
  "react": "18.2.0",
  "react-dom": "18.2.0",
  "react-native": "0.71.6",
  "react-native-svg": "13.4.0"
}

fill属性使用示例:

<Svg width={12.091} height={13.098} {...props}>
  <Path
    d="M11.083 1.008H9.068V0H8.061v1.008H4.03V0H3.023v1.008H1.008A1.01 1.01 0 000 2.015v10.076a1.01  1.01 0 001.008 1.008h10.075a1.01 1.01 0 001.008-1.008V2.015a1.01 1.01 0 00-1.008-1.007zm0 11.083H1.008V5.038h10.075zm0-8.061H1.008V2.015h2.015v1.008H4.03V2.015h4.03v1.008h1.008V2.015h2.015z"
    fill={colors.gray[400]}
  />
</Svg>
<Svg width={17.811} height={17.811} {...svgProps}>
  <Path
    data-name="Path 14499"
    d="M7.132.75a6.382 6.382 0 106.382 6.382A6.382 6.382 0 007.132.75z"
    fill="none"
    stroke={color ?? colors.gray[400]}
    strokeMiterlimit={10}
    strokeWidth={1.5}
  />
  <Path
    data-name="Path 14500"
    d="M12.293 12.293l4.457 4.457"
    strokeLinecap="round"
    fill="transparent"
    stroke={color ?? colors.gray[400]}
    strokeMiterlimit={10}
    strokeWidth={1.5}
  />
</Svg>

已尝试重装依赖、清除Expo/React Native缓存、直接填写颜色值,问题未解决。

原因分析

react-native-svg@13.x版本在Android端对fill属性的类型校验逻辑更严格,当传入的fill值为数字类型(如未加引号的十六进制数值、0-1的灰度数字)时,会触发Java层的类型转换错误(Double无法转为String)。

解决方案

1. 强制将动态颜色值转为字符串

确保所有绑定到fill/stroke的颜色值是字符串类型,可通过String()强制转换:

// 修正前
fill={colors.gray[400]}
// 修正后
fill={String(colors.gray[400])}

2. 检查颜色配置文件的格式

确认颜色常量均为字符串格式,避免使用数字类型:

// 错误写法(数字类型)
const colors = {
  gray: {
    400: 0x808080
  }
}
// 正确写法(字符串类型)
const colors = {
  gray: {
    400: "#808080"
  }
}

3. 排查props/svgProps中的fill属性

检查通过{...props}或{...svgProps}传入的属性中是否包含fill字段,若有需确保其为字符串类型,避免传入数字。

4. 临时降级react-native-svg(备选方案)

若上述方法无效,可暂时降级到react-native-svg@13.3.0(Expo SDK48兼容版本):

  1. 修改package.json中的依赖版本:
    "react-native-svg": "13.3.0"
    
  2. 重新安装依赖:
    npm install
    # 或 yarn install
    
  3. 清除缓存后重新启动项目:
    npx expo start --clear
    

验证方法

修改完成后,执行npx expo start --clear清除缓存并重启项目,检查错误是否消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:35:21