使用 react native 实现这一目标并没有太多工作要做。在这里,我尝试演示与您所要求的类似的视觉布局。
我们只需要监听视图的 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>
);
}
}
这里发生的是我们正在监听事件onLayout,当方向改变时触发。然后我们有状态变量,它保存屏幕的实际高度和宽度以反映方向变化。我们正在使用这个状态的高度和宽度进行视图设计。
这里发生了两件事。
- onLayout 在方向改变时被调用。
- 更改状态值后,视图将再次呈现。