首页 > 解决方案 > 基于 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;
  };

标签: androidiosreactjsreact-native

解决方案


您可以使用 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>
    );
  }
}

推荐阅读