ReactNative:
<ScrollView style={styles.container}>
<Svg
height="100"
width="100">
<Circle
cx="50"
cy="50"
r="50"
stroke="blue"
strokeWidth="2.5"
fill="green"/>
</Svg>
</ScrollView>
我想用 Animated.Value 使圆缩放。我已经尝试过这个:
let AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);
let AnimatedCircle = Animated.createAnimatedComponent(Circle);
<ScrollView style={styles.container}>
<Svg
height="100"
width="100">
<AnimatedCircle
cx="50"
cy="50"
r={this.state.animator}
stroke="blue"
strokeWidth="2.5"
fill="green"/>
</Svg>
</ScrollView>
然后闪退,没有错误。
我该怎么办?
<小时/>2016年8月24日更新
我找到了一种新方法来代替 requestAnimationFrame :
构造函数:
this.state = {
animator: new Animated.Value(0),
radius: 1,
};
this.state.animator.addListener((p) => {
this.setState({
radius: p.value,
});
});
渲染:
<Circle
cx="50"
cy="50"
r={this.state.radius}
stroke="blue"
strokeWidth="2.5"
fill="green"/>
但是这里the guides给出了谨慎使用它的建议,因为它可能会对 future 的性能产生影响。
那么最好的方法是什么?
最佳答案
使用 setNativeProps
获得更好的性能。
我做了一些更多的修改,发现了一种使用 addListener
和 setNativeProps
的性能更高的方法。
构造函数
constructor(props) {
super(props);
this.state = { circleRadius: new Animated.Value(50) };
this.state.circleRadius.addListener( (circleRadius) => {
this._myCircle.setNativeProps({ r: circleRadius.value.toString() });
});
setTimeout( () => {
Animated.spring( this.state.circleRadius, { toValue: 100, friction: 3 } ).start();
}, 2000)
}
渲染
render() {
return(
<Svg height="400" width="400">
<AnimatedCircle ref={ ref => this._myCircle = ref } cx="250" cy="250" r="50" fill="black" />
</Svg>
)
}
结果
这就是 2 秒(2000 毫秒)超时触发时动画的样子。
因此,您需要更改的主要内容是在监听器中使用 setNativeProps
而不是使用 setState
。这会进行 native 调用并绕过重新计算整个组件,在我的例子中,这非常复杂且缓慢。
感谢您引导我走向倾听者的道路!
关于svg - 如何在react-native中使用Animated制作svg动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39094349/