首页 文章

React Native:使用ScrollView时的垂直居中

提问于
浏览
32

我正在使用React Native,一旦我引入ScrollView,我就无法保留元素的垂直居中 . 为了演示,我使用React Native Playground创建了3个应用程序 . 所有示例都有2页,可以通过点击蓝色按钮来切换它们 .

Example 1:

第一个示例显示了在第2页上垂直居中的块 . 这是因为容器已应用这些样式:

flex: 1,
flexDirection: 'column',
justifyContent: 'center',

https://rnplay.org/apps/lb5wSQ

但是,有's a problem as soon as you switch to page 2, because the entire content of the page doesn' t适合,所以我们需要一个 ScrollView .

Example 2

在这个例子中,我将所有内容都包装在ScrollView中 . 这允许第2页滚动,但现在我丢失了第1页的垂直居中 .

https://rnplay.org/apps/DCgOgA

Example 3

为了尝试恢复第1页的垂直居中,我将 flex: 1 应用于ScrollView的 contentContainerStyle . 这修复了第1页的垂直居中,但我不再能够一直向下滚动到第2页的底部 .

https://rnplay.org/apps/LSgbog

我如何解决这个问题,以便我在第1页上获得元素的垂直居中,但仍然可以让ScrollView一直滚动到第2页的底部?

5 回答

  • 23

    我用flexGrow而不是flex解决了这个问题

    <ScrollView contentContainerStyle={{flexGrow: 1}}>

    这使得内容容器拉伸以填充ScrollView但不限制最大高度,因此当内容扩展ScrollView的边界时仍可以正确滚动

  • 1

    这是我的方法:

    使用带有 flex : 1 的外部容器,然后滚动视图需要 {flexGrow : 1, justifyContent : 'center'} 使用 contentContainerStyle ,而不是 style .

    <View style={styles.mainContainer}>
      <ScrollView
        contentContainerStyle={{flexGrow : 1, justifyContent : 'center'}}>
          <View style={styles.scrollViewContainer}>
            //Put your stuff here, and it will be centered vertical
          </View>
      </ScrollView>
    </View>
    

    样式:

    const styles = StyleSheet.create({scrollView : {
    height : Dimensions.get('window').height, }, mainContainer : {
    flex : 1 }, scrollViewContainer : { }, })
    
  • 75

    有一个新的解决方案(不幸的是目前只有iOS) - 我们可以在Scrollview上使用centerContent prop .

  • 4

    EDIT: 您现在可以使用 <ScrollView contentContainerStyle={{flexGrow: 1}}> .

    对于不支持 flexGrow 的旧版React Native,请使用以下解决方案 .


    我发现为iOS和Android可靠地执行此操作的唯一方法是将内部视图的 minHeight 设置为 ScrollView 的大小 . 例如:

    <ScrollView
        style={{flex: 1}}
        contentContainerStyle={{minHeight: this.state.minHeight}}
        onLayout={event => this.setState({minHeight: event.nativeEvent.layout.height})}
    >
    

    注意:为简单起见,我在上面列出了上面的样式和函数,但您可能希望对不变的值使用常量引用并记住更改的样式以防止不必要的重新呈现 .

    const {minHeight} = this.state;
    // Manually memorise changing style or use something like reselect...
    if (this.lastMinHeight != minHeight) {
        this.lastMinHeight = minHeight;
        this.contentContainerStyle = {minHeight: minHeight}
    }
    <ScrollView
        style={styles.scrollViewStyle}
        contentContainerStyle={this.contentContainerStyle}
        onLayout={this.onScrollViewLayout}
    >
    
  • 4

    为什么不在ScrollView中仅包装第二页?

    return (
        <ScrollView >
            <View style={styles.lipsum}>
                {this.renderButton()}
                <Text style={styles.lipsumText}>{lipsumText}</Text>
            </View>
        </ScrollView>
      );
    

    只需修改你的第一个例子,它就像一个魅力:)

相关问题