如何在 React Native 中按百分比值对视图的宽度进行动画处理?

2024-03-26

我在 React Native 中有一个 Animated.View,我正在为其宽度设置动画。

const pollRef = useRef(new Animated.Value(0)).current;

const resultWidth = ((votes/totalVotes)*100).toFixed(0)  // GET A PERCENTAGE VALUE

const AnimateResult = () => {
    Animated.timing(pollRef, {
        toValue: resultWidth,
        duration: 3000,
        useNativeDriver: false
    }).start();
};

useEffect(() => {
    AnimateResult()
},[])

<Animated.View 
    style={{
        position: 'absolute',
        top: 0,
        left: 0,
        height: '100%',
        width: pollRef,
        backgroundColor: '#155A8B',
    }}
/>

resultWidth(因此 pollRef)的值是 100。元素的宽度动画效果很好,除了它正确地将 100 视为绝对值并将宽度动画化为 100 像素之外,而我想将其表示为百分比。无论我在样式对象中使用什么语法,我似乎都无法做到。

我尝试过类似的事情:

style={{
    ...
    width: "'"+pollRef+"%'"
    ...
}}

and

style={{
    ...
    width: `${pollRef}%`,
    ...
}}

但两者都不起作用。我还注意到变量周围似乎有空格 - 如果我控制台日志:

console.log('pollRef:',pollRef,'X')

输出是:

pollRef: 0 X

这可能会使在末尾添加百分号变得更加困难。

非常感谢任何帮助。


I think https://stackoverflow.com/a/48741068/12637199 https://stackoverflow.com/a/48741068/12637199回答你的问题。

您需要使用插值将数字转换为字符串。

你可以只拥有:

const animation = new Animated.Value(0);
const inputRange = [0, 100];
const outputRange = ["0%", "100%"]

const animatedWidth = animation.interpolate({inputRange, outputRange});

然后像这样使用它:

width: animatedWidth,
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 React Native 中按百分比值对视图的宽度进行动画处理? 的相关文章

随机推荐