【问题标题】:React Native - Visible parent view despite having no margin in between children viewsReact Native - 尽管子视图之间没有边距,但可见父视图
【发布时间】:2021-08-23 10:02:06
【问题描述】:

我的屏幕设置类似于下面的代码

import React from 'react';
import { StyleSheet, View } from 'react-native';

const App = () => {
    const styles = StyleSheet.create({
        navContainer:{
            height:64,
            backgroundColor:'#333333',
            
        },
        rowsContainer:{
            backgroundColor:'red',
            margin:0,
            padding:0,
        },
    });

    return (
        <View>
            <View style={styles.navContainer} />
            <View style={styles.rowsContainer}>
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
                <ChildrenRow />
            </View>
        </View>
    );
};

export default App;

儿童行

const ChildrenRow = () => {

    return (
        <View 
            onLayout={(event) => {
                const {width, height} = event.nativeEvent.layout;
                console.log(`Height/Width= ${height} and ${width}`)
            }}
            style={{
                height:59,
                width:400,
                backgroundColor:'black',
                margin:0,
                padding:0,
            }}/>
    )
}

尽管没有边距(也没有填充,特意添加margin:0, padding:0),红色背景的视图在我的OPPO F9 上可见,在childrenRows 之间。在其他一些设备以及一些 Firebase 测试设备上也观察到了同样的情况。

使用 Android Studio 的布局检查器显示了更糟糕的结果,如下图所示

还在控制台上注意到,一些childrenRows 的高度奇怪地四舍五入:

here 提出了类似的问题,但我无法使用该解决方案,因为我将在每个子行添加 borderWidth,并且高度是非静态的,这可能会破坏 UI。

【问题讨论】:

    标签: css react-native


    【解决方案1】:

    发生这种情况是由于 像素网格对齐。您可以通过使用来避免这种情况

    import { PixelRatio } from "react-native";
    
    const height = PixelRatio.roundToNearestPixel(8.4)
    

    【讨论】:

    • 使用 PixelRatio 有效,虽然我只有一台物理设备要测试。在 Android Studio 的 LayoutInspector 中仍然可以看到红色背景,这是不可避免的吗?
    • 你也可以refer
    【解决方案2】:

    您的问题可能有一些解决方案。试着和他们混在一起。首先尝试将行高四舍五入为 60(有时设备会因为 UI 中的奇数而疯狂)。还可以尝试将行的父组件样式设置为flex:1, flexDirection: 'column',如果它不起作用,您可以通过将新组件制作为具有计算的高度和宽度的背景的黑色蒙版来解决这个问题,如果您有这个设置。确保它的位置是固定的或绝对的,并且它的 zIndex 小于 rows 并且大于 backgrounds 。最后一种方法有点暴力,但如果有效,它就有效。

    【讨论】:

    • 不幸的是,四舍五入到 60 并添加另一个绝对定位组件并不能隐藏红色背景。不过欣赏它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多