市面上有相应的插件 react-native-collapsible, 但它在折叠状态底部有莫名其妙的空白,且有不少bug未解决, 因而本身试着实现了一个简版。react
<View style={S.container}> <View style={{flex: 1}}> <View style={S.content} onLayout={this.onContentLayout}> { this.props.children } </View> </View> </View> const S = StyleSheet.create({ container: { overflow: 'hidden' }, content: { position: 'absolute', top: 0, left: 0, right: 0 } })
咱们须要能动态控制显示高度,会用到overflow:hidden
,而默认状态是折叠的,所以,为了获取实际内容的真实高度(不固定),需加两层嵌套,以便经过onLayout
方法提早获得展开后的高度。android
这是开启动画的前提。react-native
这里介绍两种方式flex
这是我经常使用的技巧。首先把container
里面的元素用Animated.View
封装:动画
<Animated.View style={{ height: this.state.height }}> <View style={{flex: 1}}> ... </View> </Animated.View>
其中height
初值为new Animated.Value(0)
,数值0表示彻底折叠。this
而后当展开时,给height
应用动画便可:插件
Animated.timing( this.state.height, { toValue: newHeight, duration: this.props.duration || 300, easing: this.props.easing || Easing.linear } ).start()
这里newHeight
为新的高度值,好比第一步中经过onLayout
获得的真实高度。调试
反之亦然,折叠时,再设为0便可。code
这是从reactnativecode.com上学到的技巧,原做者不详。orm
这种方法不须要再次封装,代码相对简洁得多。这回咱们直接在container
上设置height
:
<View style={[ S.container, { height: this.state.height } ]}> ... </View>
而后当折叠或展开时,设定动画并更新高度值:
LayoutAnimation.configureNext( LayoutAnimation.Presets.easeInEaseOut ) this.setState({ height: newHeight })
在安卓机上,须要手动开启动画:
if ( Platform.OS === 'android' ) { UIManager.setLayoutAnimationEnabledExperimental(true) }
尽管设置了overflow:hidden
,安卓下内容仍然会溢出一部分,而后和下方的内容层叠了,丑爆。
不能说overflow无效,但又不彻底符合预期,试了多种方法包括改结构,均无效,太认人沮丧了。
为了方便调试,就加了背景色,竟然好了。莫名其妙的就行了!
因此解决方法是——设定背景色。
over