React Native中ScrollView下方无法显示Button问题求助
我无法将Button组件显示在ScrollView组件的下方,请问可能是什么原因?相关代码如下:
return ( <View style={{width: width, height: undefined}}> <ScrollView style={{width: width, height: undefined}}> <View style={{flexDirection: 'row', width: width, flexWrap: 'wrap'}}> { this.state.photos.map((p, i) => { return ( <SelectedPhoto key={i} index={i} style={{ width: photoWidth, height: photoWidth, }} limit={this.state.supportLength} photo={p} onSelectPhoto={this.onSelectPhoto} onDeselectPhoto={this.onDeselectPhoto} /> ); }) } </View> </ScrollView> <View style={{margin: 20, marginBottom: 40}}> <Button raised onPress={this.onNext} containerViewStyle={{width: width-80}} backgroundColor={Colors.red} title='NEXT' /> </View> </View> )
嘿,我来帮你分析下几个最可能的原因,以及对应的解决办法:
ScrollView和父容器的高度约束缺失,导致ScrollView占满所有空间
你给父View和ScrollView都设置了height: undefined,在React Native的Flexbox布局里,这样的设置会让元素试图填满所有可用空间,但父容器本身没有明确的尺寸限制,最终ScrollView会把整个父容器的空间都占掉,把下面的Button给挤到可视区域之外了。解决办法很简单:给父View加上
flex: 1,让它占据屏幕的可用空间,再给ScrollView也加上flex: 1,这样ScrollView就会自动填充父容器除了Button区域之外的所有空间,Button就能正常显示在下方了。修改后的样式代码如下:<View style={{width: width, flex: 1}}> <ScrollView style={{width: width, flex: 1}}> {/* 原有ScrollView内容保持不变 */} </ScrollView> {/* Button所在的View保持不变 */} </View>(可选)检查ScrollView的内容容器样式
如果上面的方法没生效,可以试试给ScrollView添加contentContainerStyle={{flexGrow: 1}},确保ScrollView的内容容器能正确适配剩余空间,避免内容过长时影响外部布局。确认Button组件的样式是否异常
你用的Button看起来像是第三方组件(比如react-native-elements的Button),可以检查下它的默认样式或者你设置的containerViewStyle有没有包含position: 'absolute'这类会让元素脱离正常文档流的属性——不过你这里只设置了宽度,这个可能性不大,但可以作为排查的最后一步。
总的来说,最核心的问题就是布局的flex属性没设置正确,调整后应该就能让Button正常显示在ScrollView下方了。
内容的提问来源于stack exchange,提问作者Ilona Semyonov

