React Native之如何让一个自适应高度的弹层的弹框上下垂直居中

来源:互联网 发布:网络加密方式 编辑:程序博客网 时间:2024/06/05 04:46

需求描述:



弹层中的弹框中银行标题以及内容都是接口请求的数据,目前布局是标题框和底部确定按钮是高度和宽度固定,中间的内容部分给了最低高度并且可以随内容增多而高度自适应。现在,产品需要这个不定高度的弹框可以垂直居中显示。尝试的解决办法有以下两种:

方案一:

由于我使用的是Animated动画,首先让遮罩层淡入,再让弹框从下到上的上移,使用的是将弹框绝对定位,需要bottom值来确定弹框上移的距离。使用React Native中的View组件的onLayout属性,去动态获取这个弹框的高度:



具体的核心代码如下:

render层:

<View style={styles.viewContainer} onLayout={this._boxLayout.bind(this)}> //......</View>

方法层:

_boxLayout(event){     this.setState({         boxHeight : event.nativeEvent.layout.height})}


初始化:

constructor(props) {        super(props);        this.props = props;        this.state = {            bottom: new Animated.Value(0),            BgOpacity: new Animated.Value(0),            boxHeight: deviceHeight*0.5 - 107,        }}


弹层显示方法:

showModal() {        var _this = this;        var bottom = deviceHeight*0.5 - this.state.boxHeight*0.5;        this.CMModal.showModal(function () {            Animated.timing(          // Uses easing functions                _this.state.BgOpacity,    // The value to drive                {toValue: 1, duration: 300}            // Configuration            ).start();            Animated.timing(          // Uses easing functions                _this.state.bottom,    // The value to drive                {toValue: bottom, duration: 300}            // Configuration            ).start(            );        });}


这样解决的方案的弊端:

因为onLayout是需要在加载之后判断布局是否有变化之后才开始执行,所以显示效果就是第一次弹层加载出来之后,才能计算出这个弹框的高度,并开始计算这个bottom值。所以,第一次显示的bottom值仍然是初始化的bottom值,只有第二次点击的时候才是正确的bottom值是上下垂直居中的。


方案二:

可以直接使用React Native中的Modal,然后使用Modal中的animationType为slide或者fade,Modal层中包裹的View就可以直接用alignItems:'center'就可以达到垂直居中了。
核心代码如下:

render层:

<Modal       animationType={'fade'}       transparent={true}       visible={this.state.modalVisible}       onRequestClose={() => {       this.hideModal();}}>            <View style={[styles.modal, {opacity: 1}]}>               //...            </View></Modal>

隐藏显示方法层:

constructor(props) {        super(props);        this.state = {            modalVisible: false,        }    }    showModal() {        this.setState({            modalVisible: true,        })    }    hideModal() {        this.setState({            modalVisible: false,        })}


具体源码,请看我的github:
https://github.com/spicyboiledfish/Elastic-Layer


阅读全文
1 0
原创粉丝点击