react-native 动画Animated,高度变化的动画

mac2024-05-13  30

在react-native中我们使用Animated来编写动画的代码。

参考文档:react-native 动画api

在项目实践中,用到的是最简单的Animated.timing,实现view组件根据高度变化的过渡动画。

如图,点击收起的时候,日历高度变化,在高度变化的过程中有个动画过渡的效果。

同样,收起以后,再点击展开也会有一个高度变化的动画过渡效果。

以下是代码的实现

1.引入Animated

import {Animated} from ‘react-native’

2.设置日历的初始maxHeight,初始化Animated

constructor(props) { super(props) this.state = { calHeight: new Animated.value(500), calShow: true } this.fadeOutAnimated = Animated.timing( this.state.calHeight,{ toValue: 160, duration: 1500 } ); }

3、定义展开收起的方法

//收起 _packUpCal(){ this.fadeOutAnimated.start( () => this.state.calHeight.setValue(160)) setTimeout(() => { this.setState({calShow:false}) }, 1500) } //展开 _spreadOut(){ this.fadeOutAnimated.start( () => this.state.calHeight.setValue(getPixel.px2dp(500))) setTimeout(() => { this.setState({calShow:true}) }, 1500) }

4、在render中对日历组件进行改版

<Animated.View style={{maxHeight:this.state.calHeight}}> </Animated.View>

5、绑定展开收起的点击事件

<View style={styles.packup}> {this.state.calShow? <Text onPress={this._packUpCal.bind(this)} style={{color: '#fff',fontSize: 16}}>收起</Text>: <Text onPress={this._spreadOut.bind(this)} style={{color: '#fff',fontSize: 16}}>展開</Text>} </View>

若有疑问,可留言! 如有帮助,可给请作者的一杯咖啡添砖加瓦:

最新回复(0)