简体   繁体   English

如何使用功能组件检测本机应用程序中的屏幕方向变化

[英]How to detect screen orientation change in react-native app with a funtion component

I'm making a calculator App for react-native and I want to render different layout for buttons in landscape and portrait mode, how can I do it in a function component我正在为 react-native 制作一个计算器应用程序,我想在横向和纵向模式下为按钮呈现不同的布局,我该如何在函数组件中做到这一点

my return:我的回报:

return (
          <View style={styles.container}>

              <View style={styles.resultContainer}>
                    <Text style={styles.resultText}>
                        {displayValue}
                    </Text>
              </View>

              <View style={styles.inputContainer } >
                  {renderButtons()}

              </View>

          </View>

             );

and my RenderButtons funtion和我的 RenderButtons 功能

renderButtons = () =>{

        height = Dimensions.get('window').height
        width = Dimensions.get('window').width

      if(height > width){

        let layouts = buttons.map((buttonRows,index)=>{
            let rowItem = buttonRows.map((buttonItems,buttonIndex)=>{
                return <InputButton
                value={buttonItems}
                handleOnPress={handleInput.bind(buttonItems)}
                key={'btn-'+ buttonIndex}/>
            });
            return <View style={styles.inputRow} key={'row-' + index}>{rowItem}</View>
        });

        return layouts
      }
      else 
      {
        let layouts = buttons_landscape.map((buttonRows,index)=>{
          let rowItem = buttonRows.map((buttonItems,buttonIndex)=>{
              return <InputButton
              value={buttonItems}
              handleOnPress={handleInput.bind(buttonItems)}
              key={'btn-'+ buttonIndex}/>
          });
          return <View style={styles.inputRow} key={'row-' + index}>{rowItem}</View>
      });

      return layouts

      }
    }

of course (height > width) condition doesn't work because apparently the values are undefined, I'm kinda new to JS so please don't be to harsh on me for not knowing the obvious当然(高度 > 宽度)条件不起作用,因为显然这些值是未定义的,我对 JS 有点陌生,所以请不要因为不知道明显的原因而对我苛刻

You can use react-native-orientation-locker您可以使用react-native-orientation-locker

import Orientation from 'react-native-orientation-locker';


  _onOrientationDidChange = (orientation) => {
    if (orientation == 'LANDSCAPE-LEFT') {
      //do something with landscape left layout
    } else {
      //do something with portrait layout
    }
  };

  componentWillMount() {
    //The getOrientation method is async. It happens sometimes that
    //you need the orientation at the moment the js starts running on device.
    //getInitialOrientation returns directly because its a constant set at the
    //beginning of the js code.
    var initial = Orientation.getInitialOrientation();
    if (initial === 'PORTRAIT') {
      //do stuff
    } else {
      //do other stuff
    }
  },

  componentDidMount() {

    Orientation.getAutoRotateState((rotationLock) => this.setState({rotationLock}));
    //this allows to check if the system autolock is enabled or not.

    Orientation.lockToPortrait(); //this will lock the view to Portrait
    //Orientation.lockToLandscapeLeft(); //this will lock the view to Landscape
    //Orientation.unlockAllOrientations(); //this will unlock the view to all Orientations

    //get current UI orientation
    /*
    Orientation.getOrientation((orientation)=> {
      console.log("Current UI Orientation: ", orientation);
    });

    //get current device orientation
    Orientation.getDeviceOrientation((deviceOrientation)=> {
      console.log("Current Device Orientation: ", deviceOrientation);
    });
    */

    Orientation.addOrientationListener(this._onOrientationDidChange);
  },

  componentWillUnmount: function() {
    Orientation.removeOrientationListener(this._onOrientationDidChange);
  }

Another approach can be Here另一种方法可以在这里

You can use this library react-native-orientation你可以使用这个库react-native-orientation

Example:例子:

import Orientation from 'react-native-orientation';

 const AppScreen = () => {
  // ...

  const [deviceOrientation, setDeviceOrientation] = React.useState('');

  React.useEffect(() => {
    // The getOrientation method is async. It happens sometimes that
    // you need the orientation at the moment the JS runtime starts running on device.
    // `getInitialOrientation` returns directly because its a constant set at the
    // beginning of the JS runtime.

    // this locks the view to Portrait Mode
    Orientation.lockToPortrait();

    // this locks the view to Landscape Mode
    // Orientation.lockToLandscape();

    // this unlocks any previous locks to all Orientations
    // Orientation.unlockAllOrientations();

    Orientation.addDeviceOrientationListener(handleChangeOrientation);

    return () => {
      Orientation.removeAllListeners(handleChangeOrientation);
      console.log('Bye see you soon ! 👋');
    };
  }, []);


  const handleChangeOrientation = orientation => {
    console.log(' Device orientation change to:', orientation);
    setDeviceOrientation(orientation);
  };

  return (
    <View style={{flex: 1}}>
      <Text>{deviceOrientation}</Text>
    </View>
  );
};

export default AppScreen;
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM