Created
February 3, 2018 14:22
-
-
Save bbandydd/c2833ee7e848a6bebc0550c70f4db7ac to your computer and use it in GitHub Desktop.
Dimensions detect orientation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component } from 'react'; | |
| import { | |
| Platform, | |
| StyleSheet, | |
| Text, | |
| View, | |
| Dimensions, | |
| } from 'react-native'; | |
| import styled from 'styled-components/native'; | |
| const StatusBarBackground = styled.View` | |
| height: 20; | |
| backgroundColor: #fff; | |
| `; | |
| const Text1 = styled.Text` | |
| color: red; | |
| `; | |
| // 抓取目前裝置的寬高,用來判斷現在是直向或橫向 | |
| const isOrientationLandscape = ({ width, height }) => width > height; | |
| export default class App extends Component<{}> { | |
| // 預設state抓取目前裝置轉向 | |
| state = { | |
| isLandscape: isOrientationLandscape(Dimensions.get('window')), | |
| }; | |
| // 使用Dimensions並加入Listener,轉向時執行handleOrientationChange | |
| componentDidMount() { | |
| Dimensions.addEventListener('change', this.handleOrientationChange); | |
| } | |
| // Component移除時並移除Listener | |
| componentWillUnmount() { | |
| Dimensions.removeEventListener('change', this.handleOrientationChange); | |
| } | |
| // 更新state | |
| handleOrientationChange = ({ window }) => { | |
| this.setState({ | |
| isLandscape: isOrientationLandscape(window) | |
| }); | |
| } | |
| render() { | |
| return ( | |
| <View> | |
| { | |
| // 當裝置為直向時才加入<StatusBarBackground /> | |
| !this.state.isLandscape && <StatusBarBackground /> | |
| } | |
| <Text1> | |
| Welcome to React Native! | |
| </Text1> | |
| </View> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment