React-本机-SVG:当给定不同颜色时,LinearGradient不会在组件之间更改

r9f1avp5  于 2022-11-30  发布在  React
关注(0)|答案(1)|浏览(127)

我有一个使用react-native-svg生成方形线性渐变的组件。当我传入不同的色调颜色时,它保持相同的颜色。
我尝试过的事情:

  • 传入十六进制而不是hsl颜色,问题仍然出现

我错过了什么?
世博小吃:https://snack.expo.dev/@paulwongx/react-native-svg_color_stop_issue
Gradient.js

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

export default function Gradient({hue}) {
  return (
        <Svg width={128} height={128} viewBox="0 0 24 24">
            <Defs>
                <LinearGradient id="gradient" 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(#gradient)" />
        </Svg>
  );
}

App.js

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Gradient from './Gradient';

export default function App() {
  return (
    <View style={{flexDirection: "row", flexWrap: "wrap"}}>
      <Gradient hue={20} />
      <Gradient hue={50} />
      <Gradient hue={100} />
      <Gradient hue={150} />
      <Gradient hue={200} />
      <Gradient hue={250} />
      <Gradient hue={300} />
      <Gradient hue={350} />
    </View>
  );
}

输出量:

查看Inspect Element中呈现的代码,组件显示不同的色调,但它们都呈现相同的颜色。

// first component
<stop offset="0" stop-color="hsl(20, 100%, 74%)"></stop>
<stop offset="1" stop-color="hsl(20, 100%, 55%)"></stop>

// last component
<stop offset="0" stop-color="hsl(350, 100%, 74%)"></stop>
<stop offset="1" stop-color="hsl(350, 100%, 55%)"></stop>
tkclm6bt

tkclm6bt1#

我认为你必须给线性梯度一个唯一的id,问题是id总是一样的。

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

export default function Gradient({hue, id}) {
  return (
        <Svg width={128} height={128} viewBox="0 0 24 24">
            <Defs>
                <LinearGradient id={`gradient_${id}`} 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(#gradient_${id})`} />
        </Svg>
  );
}

然后呢

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Gradient from './Gradient';

export default function App() {
  return (
    <View style={{flexDirection: "row", flexWrap: "wrap"}}>
      <Gradient hue={20} id="first" />
      <Gradient hue={50} id="second" />
    </View>
  );
}

相关问题