首页 > 解决方案 > 绝对定位的 View 在 react-native 中不能作为覆盖层

问题描述

在 react-native 中添加了一个绝对定位的透明视图,以在异步 api 调用时显示进度加载器。但是覆盖层后面的输入和按钮仍然可以按下和响应。

<SafeAreaView style={styles.container}> 
     {this.state.isLoading &&
        <View
            style={{
               position: 'absolute', elevation: 5, backgroundColor: 'rgba(0,0,0,0.3)',
               top: 0, bottom: 0, left: 0, right: 0,
               zIndex:10
             }} 
        />
     }
     <View style={{ flexGrow: 5, flexShrink: 5, flexBasis: 100, alignItems: 'center' }}>
        <Image style={{ width: 200, flex: 1 }} source={require('res/images/one.png')} resizeMode='contain' />
    </View>

    <View style={{ flexGrow: 1, paddingLeft: 30, paddingRight: 30 }}>
        <Item regular>
            <Input
                placeholder="username123"
                autoCompleteType="username"
                onChangeText={(username) => this.setState({ username })}
                value={this.state.username}
            />
        </Item>
        <Button block onPress={this.onClick}
            style={styles.button}>
            <Text style={styles.buttonText}>Login</Text>
        </Button>
    </View>
</SafeAreaView>

PS:没有elevation:5按钮出现在覆盖上方(使用原生按钮/控件)。没有 zIndex 的图像将出现在叠加层之上

标签: react-nativenative-base

解决方案


发生这种情况的原因是 React 组件树是如何呈现的,因为您在 Input 字段上方显示叠加层,而 Button 它们仍然在叠加层上方,您需要做的就是将叠加层从顶部移动到底部。

<SafeAreaView style={styles.container}> 
     <View style={{ flexGrow: 5, flexShrink: 5, flexBasis: 100, alignItems: 'center' }}>
        <Image style={{ width: 200, flex: 1 }} source={require('res/images/one.png')} resizeMode='contain' />
    </View>

    <View style={{ flexGrow: 1, paddingLeft: 30, paddingRight: 30 }}>
        <Item regular>
            <Input
                placeholder="username123"
                autoCompleteType="username"
                onChangeText={(username) => this.setState({ username })}
                value={this.state.username}
            />
        </Item>
        <Button block onPress={this.onClick}
            style={styles.button}>
            <Text style={styles.buttonText}>Login</Text>
        </Button>
    </View>

    {/* Moved below the form */}

    {this.state.isLoading &&
       <View
            style={{
               position: 'absolute', elevation: 5, backgroundColor: 'rgba(0,0,0,0.3)',
               top: 0, bottom: 0, left: 0, right: 0,
               zIndex:10
             }} 
        />
     }
</SafeAreaView>

推荐阅读