【问题标题】:Adjust the scrollview height dynamically at runtime在运行时动态调整滚动视图高度
【发布时间】:2021-04-13 19:22:17
【问题描述】:

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

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

  • MySubComponent,
  • Text
  • Image 组件

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

为了实现这一点,我的计划是禁用 ScrollViewautomaticallyAdjustContentInsets,正如您从下面的代码 sn-p 中看到的那样。然后,有一个状态变量来保存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>)
}

【问题讨论】:

    标签: react-native react-native-scrollview


    【解决方案1】:

    &lt;ScrollView&gt; 中的所有内容包装在&lt;View&gt; 中。然后使用 onLayout 获取该父 View 的高度。

      const handleScrollContentLayout = (e) => {
        const { height } = e.nativeEvent.layout
        setScrollLayoutHeight(height)
      }
    
    ...
    
    <View onLayout={handleScrollContentLayout}>
    { /* scrollView content... */ }
    </View>
    

    然后您可以根据需要使用scrollLayoutHeight在运行时设置高度。

    【讨论】:

    • 谢谢。它有效,但是,内容高度看起来比整体实际内容高一倍。我必须 setScrollLayoutHeight(height*0.5) 以避免在 ScrollView 内容底部出现大的空白。
    • console.log 高度值并检查它是否改变。通常,onLayout 会被多次调用,并且最终值通常是正确的。就我而言,我在第一次渲染时收到 0。因此,我使用 useState 钩子将返回的高度设置为状态以进行相应的更新。
    • reactnative.dev/docs/direct-manipulation#measurecallback -> 也可以查看这个回调。这是动态获取高度的另一种选择。不过,我以前没用过。
    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2016-03-30
    相关资源
    最近更新 更多