首页 > 解决方案 > 尝试动态设置 viewBox 宽度/高度

问题描述

我正在尝试使用 React Native Animated 以编程方式放大 SVG。目前我正在测试代码,证明一些事情。我似乎无法传递使用 React.useState(new Animated.Value(0) 设置的 viewBox 大小

我收到一个错误:无效的viewBox道具:0 0 [object Object][object Object]

这是我的一些代码:

const AnimatedSVG = Animated.createAnimatedComponent(Svg);

const [widthValue, setWidthValue] = React.useState(new Animated.Value(1920));

const [heightValue, setHeightValue] = React.useState(new Animated.Value(1080));

const segmentClick = (event, someParameter) => {
      Animated.timing(widthValue, {
        toValue: 3000,
        duration: 1000,
        useNativeDriver: true,
        easing: Easing.linear,
      }).start();
  };

<AnimatedSVG x="0px" y="0px" viewBox={`0 0 ${widthValue} ${heightValue}`} style="enable-background:new 0 0 1920 1080; ">

如前所述,我得到的错误: Invalid viewBoxprop:0 0 [object Object][object Object] 似乎 widthValue 和 widthHeight 是对象。但是如果我 console.log 他们我可以看到他们打印为 1920 / 1080

我怀疑我错过了一些非常简单的东西,但在网上找不到答案。

标签: react-nativereact-animated

解决方案


您可以尝试创建动画值的侦听器,并更新状态:

const [widthValue, setWidthValue] = React.useState(1920);
const widthAnimated = React.useRef(new Animated.Value(1920)).current;

const segmentClick = (event, someParameter) => {
      widthAnimated.addListener((e) => setWidthValue(e.value)) // Add listener
      Animated.timing(widthAnimated, {
        toValue: 3000,
        duration: 1000,
        useNativeDriver: true,
        easing: Easing.linear,
      }).start();
};

在 SVG 中:

<AnimatedSVG x="0px" y="0px" viewBox={`0 0 ${widthValue} ${heightValue}`} style="enable-background:new 0 0 1920 1080; ">

对身高做同样的事情。


推荐阅读