現在有這樣一種情況是在開發中經常遇到的,外層是一個scrollview組件,組件內部有很多組件高度不固定,最後是一個按鈕,在不滿一個屏幕時按鈕位居底部,當超過一屏幕時按鈕位於組件的末尾,可以隨着scrollview滾動。
效果圖:
方法:
如果使用絕對定位佈局position:absolute肯定是不可以,因爲按鈕會始終位於底部,當組件超過一個屏幕時按鈕依然在屏幕底部,不會隨着scrollview組件滾動。
然後想到flex佈局裏面有一個space-betweent類型,那麼是不是可以將scrollview內部的組件分爲兩部分,按鈕與其他組件。然後在其他組件的外層套一個view,在使用space-betweent佈局就可以了。然後進行嘗試,發現在不滿一屏幕時,按鈕可以在底部顯示。當組件高度超過一個屏幕時,發現還是不行。但是我覺的我的思路大概是正確的,於是尋找問題出在哪裏。
後來還是被我發現了,原來問題出現在flex:1 這裏。
其實這個關鍵在於scrollview內部組件的高度是多少,我們可以獲取到組件內部的高度,如果超過一個屏幕就不設置flex:1這個屬性,不超過就設置這個屬性。
核心代碼如下:
layout = (event)=>{
let { x, y, width, height } = event.nativeEvent.layout;
if(height>(HEIGHT-SCALE(94)-SCALE(20)-SCALE(120))){
this.setState({
flex:false,
})
}else{
this.setState({
flex:true,
})
}
console.log('height',height,'SCREENHEIGHT',HEIGHT-SCALE(94)-SCALE(20)-SCALE(120));
};
<ScrollView
overScrollMode = {'always'}
contentContainerStyle={[{justifyContent:'space-between'},this.state.flex?{flex:1}:null]}
keyboardDismissMode = {'on-drag'}
showsVerticalScrollIndicator={false}>
<View onLayout={this.layout}>
{this.renderRest()}
{this.renderRule()}
<View style={{marginTop:SCALE(20),marginLeft:SCALE(20),marginRight:SCALE(20),backgroundColor: 'white'}}>
{this.renderTip()}
{this.renderSeparator()}
{this.renderType()}
{this.renderSeparator()}
{this.renderDate()}
{this.renderSeparator()}
{this.renderCause()}
</View>
</View>
{this.renderBtn()}
</ScrollView>
完整代碼僅供參考:
https://github.com/wuyunqiang/ReactNativeUtil/issues/7