【问题标题】:FlexDirection Change Based on Orientation Change in React-Native基于 React-Native 中方向变化的 FlexDirection 变化
【发布时间】:2020-06-27 12:55:14
【问题描述】:

我的代码:

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') 没有奏效 我只想更新 My View 渲染而不是其他 Api Stuff。

我要换flexDirection: isPortrait ? ('column') : ('row')

export const isPortrait = () => {
    const dim = Dimensions.get('screen');
    return dim.height >= dim.width;
  };

【问题讨论】:

    标签: android ios reactjs react-native


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      相关资源
      最近更新 更多