React Native如何对文本和图像进行动画处理

时间:2020-09-04 19:45:42

标签: react-native animation

大家好,我只想给文本和图像添加动画。我写的这段代码是在开始时设置动画的。当我更新状态时,动画仅更改图像和文本就消失了。我该如何解决。

//the package I installed from npm
import * as Animatable from 'react-native-animatable';

//the images array changes by state
var arr=[{image:require('./assets/img1.png')},{image:require('./assets/img2.png')},{image:require('./assets/img3.png')}];

//The initial state
state = { 
  uri: require('./assets/img1.png'),
  message:"-",
  img_rank:0
};

//In onpress method of TocuhableOpacity
<TouchableOpacity
     onPress={() => {

const randomIndex = Math.floor(Math.random() * 3);

//state of message
this.setState({ message: "Act1" });

//state of image rank from the array
this.setState({ img_rank: randomIndex })
    ...

显示文字和图像

//it's showing the image with animation at the beginning
<Animatable.Image source={arr[this.state.img_rank].image}  animation="zoomInUp">      
</Animatable.Image>

//the text but it's not animating

<Animatable.Text   animation="zoomInUp">
   <Text>{this.state.message} </Text>
</Animatable.Text>

谢谢。

1 个答案:

答案 0 :(得分:0)

首先,将动画组件的ref放入类中的变量中,例如 animatedImageRef

<Animatable.Image 
   ref={r => this.animatedImageRef = r}
   source={arr[this.state.img_rank].image}  
   animation={this.state.img_rank ? 'zoomInUp' : undefined}>      
</Animatable.Image>

然后,在您的onPress函数中,使用此引用再次为组件添加动画。

this.animatedImageRef.startAnimation(500, 0, () => { })