android - 基于 React-Native 中方向变化的 FlexDirection 变化
问题描述
我的代码:
import React, { PureComponent } from 'react'
import { StyleSheet, View } from 'react-native'
import {
isPortrait
} from './Constants'
export default class TwoVideoView extends PureComponent {
render() {
return (
<View style={styles.conatiner}>
<View style={[styles.videoHalfView, {backgroundColor: 'white'}]}>
</View>
<View style={[styles.videoHalfView, {backgroundColor: 'gray'}]}>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
conatiner: {
flex: 1,
backgroundColor: 'red',
flexDirection: isPortrait ? ('column') : ('row')
},
videoFullView: {
width: '100%',
height: '100%'
},
videoHalfView: {
width: isPortrait ? ('100%') : ('50%'),
height: isPortrait ? ('50%') : ('100%')
}
})
人像输出:
你能帮我做些什么来完成这件事吗?
我尝试添加Dimensions.addListener('change') 没有工作 我只想更新我的视图渲染而不是其他Api Stuff。
我需要改变flexDirection: isPortrait ? ('column') : ('row')
export const isPortrait = () => {
const dim = Dimensions.get('screen');
return dim.height >= dim.width;
};
解决方案
您可以使用 onLayout 属性根据容器的宽度和高度计算布局,并提供基于此的样式。
我已经更新了容器样式。你可以改变其余的
const styles = StyleSheet.create({
conatinerPortrait: {
flex: 1,
backgroundColor: 'red',
flexDirection: 'column',
},
conatinerLandscape: {
flex: 1,
backgroundColor: 'red',
flexDirection: 'row',
}
});
class TwoVideoView extends React.PureComponent {
state = {
isPortrait: true,
};
calculateDimensions = ({ nativeEvent }) => {
const { layout } = nativeEvent;
if (layout.height > layout.width) {
this.setState({
isPortrait: true,
});
} else {
this.setState({
isPortrait: false,
});
}
};
render() {
const { isPortrait } = this.state;
return (
<View
style={
isPortrait ? styles.conatinerPortrait : styles.conatinerLandscape
}
onLayout={this.calculateDimensions}>
<View
style={[styles.videoHalfView, { backgroundColor: 'white' }]}></View>
<View
style={[styles.videoHalfView, { backgroundColor: 'gray' }]}></View>
</View>
);
}
}
推荐阅读
- java - 如何从地图中获取偶数值,然后将值键添加到列表中?
- amazon-redshift - 用于动态 json 文件的 Redshift JSONPaths 文件
- java - Maven generatePackage 用于从模式定义生成类的 wsdl
- html - 用画布定位
- typescript - 为什么打字稿不能正确推断条件的泛型类型?
- openlayers - 尝试在 OpenLayers 上刷新 TileLayer
- c# - 在使用 .NET Framework 4.8 项目中将 NuGet 包内容标记为“复制到输出”
- java - 如何使用带有 Selenium 和 Java 的 XPath 提取表中迭代特定行的文本
- javascript - PWA 应用程序中的文件可以缓存多长时间以及可以缓存的文件的最大大小?
- c# - 当我将 ForeignKey 添加到另一个 DbContext 时,Ef 正在创建新表