React Native:使用ScrollVi时垂直居中

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

范例1:

第一个示例显示了在第2页上垂直居中的块。这是因为容器将以下样式应用于其上:

flex: 1,

flexDirection: 'column',

justifyContent: 'center',

[https://rnplay.org/apps/lb5wSQ]

但是,切换到页面2会出现问题,因为该页面的全部内容都不适合,因此我们需要flex: 1。

例子2

在此示例中,我将所有内容包装在ScrollView中。 这允许页面2滚动,但是现在我失去了页面1的垂直居中。

[https://rnplay.org/apps/DCgOgA]

例子3

为了尝试恢复第1页的垂直居中,我将flex: 1应用到ScrollView的contentContainerStyle。 这样可以解决第1页的垂直居中问题,但我无法一直向下滚动到第2页的底部。

[https://rnplay.org/apps/LSgbog]

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

6个解决方案

137 votes

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

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

Jake Coxon answered 2020-02-14T14:26:16Z

45 votes

这是我的方法:

使用带有flex : 1的外部容器,那么滚动视图需要使用contentContainerStyle而不是style来具有{flexGrow : 1, justifyContent : 'center'}。

contentContainerStyle={{flexGrow : 1, justifyContent : 'center'}}>

//Put your stuff here, and it will be centered vertical

样式:

const styles = StyleSheet.create({scrollView : {

height : Dimensions.get('window').height, }, mainContainer : {

flex : 1 }, scrollViewContainer : { }, })

Elden Skloss answered 2020-02-14T14:26:45Z

4 votes

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

Radek Czemerys answered 2020-02-14T14:27:05Z

4 votes

编辑:您现在可以使用minHeight。

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

我发现对iOS和Android可靠地执行此操作的唯一方法是将内部视图的minHeight设置为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}

}

style={styles.scrollViewStyle}

contentContainerStyle={this.contentContainerStyle}

onLayout={this.onScrollViewLayout}

>

SteveMellross answered 2020-02-14T14:27:42Z

1 votes

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

return (

{this.renderButton()}

{lipsumText}

);

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

Michał Kisiel answered 2020-02-14T14:28:07Z

1 votes

为了使ScrollView自身垂直居中,则需要具有以下结构:

否则,如果您想将ScrollView内容本身居中,则需要满足以下条件:

David answered 2020-02-14T14:28:32Z

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐