关于react-native的适配与布局方式

本文介绍了一种使用React Native进行布局的方法,通过利用屏幕宽度和高度以及relative相对定位,实现了一个具体的布局示例,并展示了如何根据不同屏幕尺寸进行适配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人比较倾向于利用屏幕宽度和高度以及relative相对距离来布局。

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

export default class Demo extends Component {
    render() {
        return (
            <View style={styles.container}>
                <View style={styles.navigationBar}>
                </View>
                {/*距离顶部40px,一个宽600px,高200px居中的View*/}
                <View style={[styles.sizeView,{position:'relative'}]}>
                </View>
                {/*距离左侧20px,距离顶部80px,宽度400px,高度60px*/}
                <View style={[styles.bottomLeftView,{position:'relative'}]}>
                </View>
                {/*距离bottomLeftView右侧40px,距离顶部sizeView200px,宽度40px,高度200px*/}
                <View style={[styles.bottomRightView,{position:'relative'}]}>
                </View>
            </View>
        );
    }
}

let Dimensions = require('Dimensions');
let {width,height} = Dimensions.get('window');
let Platform = require('Platform');
let StatusBar = require('StatusBar');
{/*如果UI设计师的原型图是以6S为基准,6S的屏幕宽度为1334像素,那么算出缩放比例*/}
let scale = width/1334;
let navHeight = Platform.OS === 'ios' ? 128*scale : StatusBar.currentHeight + 40*scale;


const styles = StyleSheet.create({
    container: {
        backgroundColor: 'yellow',
        width: width,
        height: height,
    },
    navigationBar: {
        backgroundColor: 'red',
        width:width,
        height:navHeight,
    },
    sizeView: {
        backgroundColor: 'green',
        marginTop: 40*scale,
        left: (width - 600*scale)/2,
        width: 600*scale,
        height: 200*scale,
    },
    bottomLeftView: {
        backgroundColor: 'blue',
        marginTop:80*scale,
        left: 20*scale,
        width: 400*scale,
        height: 60*scale,
    },
    bottomRightView: {
        backgroundColor: 'black',
        left: 20*scale + 400*scale + 40*scale,
        marginTop:200*scale,
        width: 40*scale,
        height: 200*scale,
    }
});

AppRegistry.registerComponent('Demo', () => Demo);

效果如图:
这里写图片描述

相对距离根据需求可以换成屏幕宽高的百分比,这样就可以适配各种分辨率了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值