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

react-native-svg中LinearGradient传入不同色值但组件渲染颜色不变问题

问题根因

你所有Gradient组件里的<LinearGradient>都用了固定的id="gradient",SVG的元素ID是全局生效的,页面里所有相同ID的定义只会识别第一个,所以所有Rect的fill="url(#gradient)"都统一引用了第一个组件里的渐变配置,就算后面组件的stop颜色改了也不会生效。

修复方案

给每个渐变生成唯一的ID即可,比如直接用传入的hue值拼接成唯一ID,修改后的Gradient.js代码如下:

import * as React from 'react';
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";

export default function Gradient({hue}) {
  // 用hue生成唯一ID,保证每个组件的渐变ID不重复
  const gradientId = `gradient-${hue}`
  return (
        <Svg width={128} height={128} viewBox="0 0 24 24">
            <Defs>
                <LinearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="100%">
                    <Stop offset="0" stopColor={`hsl(${hue}, 100%, 74%)`} />
                    <Stop offset="1" stopColor={`hsl(${hue}, 100%, 55%)`} />
                </LinearGradient>
            </Defs>
            <Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
        </Svg>
  );
}

如果存在hue值重复的场景,也可以用随机字符串、自增计数等方式生成唯一ID,保证每个组件的渐变ID全局唯一即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:48:02