我正在开发一个react原生项目。
我在MyComponent
中有一个ScrollView
,ScrollView
的内容包括:
- CCD_ 4
Text
Image
组件
上述组件的所有内容/数据都具有动态长度或高度。因此,我想在运行时动态调整ScrollView
的内容高度。
为了实现这一点,我的计划是禁用ScrollView
的automaticallyAdjustContentInsets
,正如您从下面的代码片段中看到的那个样。然后,使用一个状态变量来保存contentInsetBottom
的最新值。但我不确定如何计算子组件的高度,以便调用setContentInsetBottom(totalHeight)
来更新我的ScrollView
的内容高度。
(如果我知道如何计算ScrollView
的每个儿童组件的高度,我非常确信我的计划会奏效。(
有人能给我指路吗?
const MyComponent = ({myText, image}) => {
// I have a state of the contentInsetBottom for the ScrollView
const [contentInsetBottom, setContentInsetBottom] = useState(0);
// how can I get the height of each children component, sum them up & call setContentInsetBottom(totalHeight) here ?
return (
<ScrollView
automaticallyAdjustContentInsets={false}
contentInset={{top: 0, bottom: contentInsetBottom}}
style={styles.scrollView}
contentContainerStyle={styles.contentContainer}>
<MySubComponent />
<Text>{myText}</Text>
<Image source={{uri: image?.uri}}>
</ScrollView>)
}
在<View>
中包装<ScrollView>
内的所有内容。然后使用onLayout获取父视图的高度。
const handleScrollContentLayout = (e) => {
const { height } = e.nativeEvent.layout
setScrollLayoutHeight(height)
}
...
<View onLayout={handleScrollContentLayout}>
{ /* scrollView content... */ }
</View>
然后,您可以根据需要使用scrollLayoutHeight在运行时设置高度。