简体   繁体   中英

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

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 = () =>{

        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

You can use 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

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;
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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