带有React Native的iOS自适应布局

Dan*_*ani 3 ios flexbox ios-autolayout react-native

我已经和反应本地人一起工作了几个星期,而且我已经达到了我需要支持两种方向的程度.据称,flex-box应该发挥其魔力并自动调整布局以适应新的屏幕大小.然而,flex-box并没有像我希望的那样处理这些变化,我并不是说它不会做我应该做的事我说我对它不满意.

更具体一点,我在网上找到了这个例子,它基本上描述了我想解决的问题(只有他们用原生视图和自动布局来做).我希望在设备旋转(或更一般地说,大小更改)上实现布局更改,类似于应用于我链接的"迷你Instagram"示例的布局更改.

我怎么能用react-native和flex-box做到这一点?我是否应该针对不同的屏幕尺寸使用不同的组件,还是有正确的方法来实现这一目标?

Raj*_*shu 6

做反应原生没有太多工作要做.在这里,我试图展示你所要求的类似视觉布局.

在此输入图像描述

我们只需要监听onLayout视图事件,只要方向发生变化就会调用它.

通过比较Dimension.get('window')的高度和宽度,我们可以确定设备是处于纵向还是横向模式.这是简单的代码

import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
  Image,
  Dimensions
} from 'react-native';

var {height, width} = Dimensions.get('window');

export default class Com extends Component{
  constructor(){
    console.log('constructor');
    super();
    this.state = {
      layout:{
        height:height,
        width:width,

      }
    };

  }
  _onLayout = event => {

    console.log('------------------------------------------------' + JSON.stringify(event.nativeEvent.layout));

    this.setState({
      layout:{
        height:event.nativeEvent.layout.height,
        width:event.nativeEvent.layout.width,

      }
    });
  }


  render(){
    console.log(JSON.stringify(this.props));
    var imagel = this.props.list[0].src;
    var landscapeView =
                        <View style={{marginTop:20, flexDirection:'row'}}>
                          <Image source={require('./flower.jpg')} style={{height:this.state.layout.height-50, width:this.state.layout.width/2}}/>
                          <View>
                            <Text style={{backgroundColor:'gray', margin:5}}> header this is landscape view </Text>
                            <Text style={{backgroundColor:'gray',margin:5}}> footer this is portrait view  </Text>
                          </View>


                        </View>
    var portraitView = <View style={{marginTop:20}}>
                        <Text style={{backgroundColor:'gray', margin:5}}> header this is landscape view </Text>
                          <Image source={require('./flower.jpg')} style={{height:200, width:this.state.layout.width}}/>
                          <Text style={{backgroundColor:'gray',margin:5}}> footer this is portrait view  </Text>
                        </View>

    var cview =null;
    if (this.state.layout.height>this.state.layout.width) {
      cview = portraitView
    }else{
      cview = landscapeView;
    }
    return(
      <View style={{backgroundColor:'red', flex:1}}   onLayout={this._onLayout}>
      {cview}
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这里发生的事情是我们正在监听事件onLayout,这是在方向改变时触发的.然后我们有状态变量,它保持屏幕的实际高度和宽度,以反映方向的变化.我们正在使用此状态高度和宽度进行视图设计.

这里发生了两件事.

  1. 在方向更改时调用onLayout.
  2. 在更改状态值时,视图将再次呈现.