1. 程式人生 > >關於react-native的適配與佈局方式

關於react-native的適配與佈局方式

個人比較傾向於利用螢幕寬度和高度以及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);

效果如圖:
這裡寫圖片描述

相對距離根據需求可以換成螢幕寬高的百分比,這樣就可以適配各種解析度了。