【问题标题】:ScrollView minHeight to take up all the spaceScrollView minHeight 占用所有空间
【发布时间】:2016-12-19 16:36:49
【问题描述】:

我有一个ScrollView,它的内容不一定超过它的大小。假设它是一种表单,在出现错误时,它会扩展以添加错误消息,然后超出 ScrollView 大小,这就是我使用该滚动条的原因。

问题是我希望内容始终至少与 ScrollView 的大小相同。我知道 minHeight 属性,但我发现使用它的唯一方法是重新渲染,我想避免这种情况。

我正在使用 redux 进行状态管理,这就是我所拥有的

<ScrollView
  contentContainerStyle={[ownStyles.container, {minHeight: this.props.scrollHeight}]}
  style={this.props.style}
  showsVerticalScrollIndicator={false}
  onLayout={(event) => {
    scrollHeight = event.nativeEvent.layout.height;
    this.props.setScrollContentHeight(scrollHeight);
  }}
>

this.props.setScrollContentHeight 触发进入状态高度的动作,this.props.scrollHeight 表示高度。因此,在触发 onLayout 函数的第一次渲染之后,状态会使用 ScrollView 的 height 进行更新,然后我将其分配为 minHeight 到其内容。

如果我将内容的样式设置为flex: 1,那么 ScrollView 将不会滚动。

您能想出一种方法来避免出于性能目的进行第二次渲染吗?

谢谢!

【问题讨论】:

标签: javascript react-native redux react-native-flexbox


【解决方案1】:

您应该在 ScrollView 中使用 flexGrow: 1,在 ScrollView 中使用 flex: 1,以获得 ScrollAble,但至少要尽可能大 &lt;View&gt;

有一个discussion about it in react-nativetushar-singh 有一个好主意。

【讨论】:

  • 注意ScrollView不能直接使用style,但是contentContainerStyle:&lt;ScrollView contentContainerStyle={{flexGrow: 1}}&gt;
  • 另外,如果你的内部视图像我一样是 KeyboardAvoidingView,你需要使用 (或,至少我做到了)。
【解决方案2】:

已经很长时间了,但我在同样的问题上苦苦挣扎。简单的方法是在 scrollView 的 stylecontentContainerStyle 道具上使用 flexGrow: 1 而不是 flex:1。如果需要,内容将占用至少 100% 的空间和更多空间。

【讨论】:

  • 谢谢!不过contentContainerStyle 对我来说已经足够了
【解决方案3】:

这样做的几个解决方案是:

  • ScrollView 上使用minHeight(但这需要考虑屏幕尺寸才能正确渲染)
  • ScrollView contentContainerStyle 上使用flexGrow: 1,在内部内容上使用flex: 1
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
  <View style={{ flex: 1 }}>
    ...
  </View>
</ScrollView>

【讨论】:

    【解决方案4】:

    我想分享我的解决方案,对我来说,https://github.com/facebook/react-native/issues/4099 没有任何效果。我也不能在那里发表评论,因为 facebook 阻止了线程 ¬.¬!

    基本上我的解决方案是在ScrollView 组件上的contentContainerStyle 中设置flexGrow: 1,并将所有内容包装在View 组件中,并使用height 属性设置屏幕大小。这里是示例代码:

    import { Dimensions } from "react-native";
    
    let screenHeight = Dimensions.get('window').height;
    
    <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
       <View style={{height: screenHeight}}>
        ... your content here ...
       </View>
    </ScrollView>
    
    

    【讨论】:

      【解决方案5】:

      我知道这有点晚了,但我认为用 ViewminHeight 样式属性将 ScrollView 中的内容包装起来就可以了。

      【讨论】:

        【解决方案6】:
        <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
          <View style={{ flexGrow: 1 }}>
            Your content
          </View>
        </ScrollView>
        

        这对我有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-12
          • 1970-01-01
          • 1970-01-01
          • 2020-11-03
          • 1970-01-01
          • 2019-09-23
          • 2015-03-24
          相关资源
          最近更新 更多