在运行时动态调整滚动视图的高度



我正在开发一个react原生项目。

我在MyComponent中有一个ScrollViewScrollView的内容包括:

  • CCD_ 4
  • Text
  • Image组件

上述组件的所有内容/数据都具有动态长度或高度。因此,我想在运行时动态调整ScrollView的内容高度。

为了实现这一点,我的计划是禁用ScrollViewautomaticallyAdjustContentInsets,正如您从下面的代码片段中看到的那个样。然后,使用一个状态变量来保存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在运行时设置高度。

最新更新