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

Adjust the scrollview height dynamically at runtime

我正在开发一个 react-native 项目。

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

以上组件content/data都具有动态长度或高度。所以,我想在运行时动态调整 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>)
}

<ScrollView> 内的所有内容包装在 <View> 中。然后使用 onLayout 获取父视图的高度。

  const handleScrollContentLayout = (e) => {
    const { height } = e.nativeEvent.layout
    setScrollLayoutHeight(height)
  }

...

<View onLayout={handleScrollContentLayout}>
{ /* scrollView content... */ }
</View>

然后你可以根据需要使用scrollLayoutHeight来设置运行时的高度。