【问题标题】:flex not working in ScrollView in react-nativeflex 在 react-native 的 ScrollView 中不起作用
【发布时间】:2020-12-28 10:06:05
【问题描述】:

我在 react native 中有一个非常基本的样式问题

下面是我的代码:

[![return (
            <View style={{ flex: 1, backgroundColor: "blue" }}>
                <ScrollView style={{ flex: 1, backgroundColor: "blue" }}>
                    <View style={{ flex: 1, backgroundColor: "red" }}>
                        <Text>Hello</Text>
                    </View>
                    <View style={{ flex: 1, backgroundColor: "orange" }}>
                        <Text>Hello</Text>
                    </View>
                    <View style={{ flex: 1, backgroundColor: "green" }}>
                        <Text>Hello</Text>
                    </View>
                </ScrollView>
                <ScrollView style={{ flex: 1, backgroundColor: "blue" }}>
                    <View style={{ flex: 1, backgroundColor: "red" }}>
                        <Text>Hello</Text>
                    </View>
                    <View style={{ flex: 1, backgroundColor: "orange" }}>
                        <Text>Hello</Text>
                    </View>
                    <View style={{ flex: 1, backgroundColor: "green" }}>
                        <Text>Hello</Text>
                    </View>
                </ScrollView>
            </View>
        );

我只是想知道为什么我在 2 个 ScrollVie 之间会出现蓝色空间?如果我删除 ScrollView,那么我的 flex 属性工作正常。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    将您的 ScrollView 更改为:

    <ScrollView 
    ... other stuff
    // Add here
    contentContainerStyle={{
     flex: 1 // or flexGrow: 1
    }}
    >
    

    Issue on React Native repo

    【讨论】:

      【解决方案2】:

      您传递给 ScrollView 的样式应该在 ScrollView 容器中传递 像这样

      <ScrollView 
      contentContainerStyle={{
       flex: 1 // or flexGrow: 1
      }}
      > ... </ScrollView >
      

      this can help you to understand

      【讨论】:

        【解决方案3】:

        原因是您为父视图提供 flex:1 所以它需要最大屏幕高度。并且子 ScrollViews 也有 flex: 1。如果将滚动视图的背景颜色更改为其他颜色,您会注意到拉伸的是滚动视图,而不是父视图。

        您可以移除父视图的 flex 属性,这样您的 ScrollView 就不会被拉伸到占据一半屏幕。

        【讨论】: