React Native:使ScrollView的每个子级都达到最高高度 [英] React Native: Make Each Child of ScrollView Full Height
问题描述
我有一个 ScrollView
,其中有两个孩子,我希望每个孩子都是屏幕上可用空间的全部高度,这意味着视图1会填满整个屏幕,然后我向下滚动以开始查看幻灯片2的一部分.如果一直向下滚动,则只能看到幻灯片2.
I have a ScrollView
which has two children, and I want each of the children to be the full height of the available space on the screen, meaning view 1 fills the whole screen, and then I scroll down to start to see part of slide 2. If I scroll all the way down, I should only see slide 2.
我不知道如何实现这一目标.当前正在发生的事情是每个孩子都占据了可用垂直空间的一半,所以我没有任何滚动.
I can't figure out how to get this to happen. What is currently happening is that each child is filling half of the available vertical space, so I don't get any scrolling.
有什么想法可以实现这种布局吗?谢谢!
Any ideas how I can achieve this layout? Thanks!
当前用户界面: https://i.imgur.com/fZdbUSo.png
所需的用户界面:
- 滚动之前: https://i.imgur.com/EsQpVMm.png
- 完全向下滚动后: https://i.imgur.com/PfXQyfI.png
代码:
import React from "react";
import {
StyleSheet,
ScrollView,
Text,
View
} from "react-native";
const Home = () => {return (
<ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollViewContainer}>
<View style={styles.slide1}>
<Text>this should be full height</Text>
</View>
<View style={styles.slide2}>
<Text>this should also be full height, but only be visible once i scroll down</Text>
</View>
</ScrollView>
)};
const styles = StyleSheet.create({
slide1: {
justifyContent: "center",
flexGrow: 1,
backgroundColor: "blue"
},
slide2: {
justifyContent: "center",
flexGrow: 1,
backgroundColor: "green"
},
scrollView: {
flex: 1
},
scrollViewContainer: {
flexGrow: 1
}
});
export default Home;
推荐答案
我能够按照道格·沃特金斯(Doug Watkins)的建议使用 onLayout()
并更新子代的高度以使其匹配父 ScrollView
的高度:
I was able to get this to work by using onLayout()
as Doug Watkins suggested and updating the height of the children to match the height of the parent ScrollView
:
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
Text,
View,
LayoutChangeEvent
} from "react-native";
class Home extends Component {
state = {
slideHeight: 0
};
updateHeight = (e: LayoutChangeEvent) => {
this.setState({ slideHeight: e.nativeEvent.layout.height });
};
styles = StyleSheet.create({
slide1: {
justifyContent: "center",
backgroundColor: "blue"
},
slide2: {
justifyContent: "center",
backgroundColor: "green"
},
scrollView: {
flex: 1
},
scrollViewContainer: {
flexGrow: 1
}
});
render () {
return (
<ScrollView style={this.styles.scrollView} contentContainerStyle={this.styles.scrollViewContainer} onLayout={this.updateHeight}>
<View style={[this.styles.slide1, {height: this.state.slideHeight}]}>
<Text>this should be full height</Text>
</View>
<View style={[this.styles.slide2, {height: this.state.slideHeight}]}>
<Text>this should also be full height, but only be visible once i scroll down</Text>
</View>
</ScrollView>
)
}
};
export default Home;
这篇关于React Native:使ScrollView的每个子级都达到最高高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!