美文网首页
React- Native 特定平台扩展名, 及平台检测

React- Native 特定平台扩展名, 及平台检测

作者: 有情怀的程序猿 | 来源:发表于2017-03-01 14:31 被阅读0次

特定平台扩展名,

React Native会检测某个文件是否具有.ios.或是.android.的扩展名,然后根据当前运行的平台加载正确对应的文件

BigButton.ios.js
BigButton.android.js

这样命名组件后你就可以在其他组件中直接引用,而无需关心当前运行的平台是哪个。

import BigButton from './components/BigButton';

React Native会根据运行平台的不同引入正确对应的组件。

Platform.select() 根据平台的不同使用使用不同的样式或者组件

它可以以Platform.OS为key,从传入的对象中返回对应平台的值

  • 比如: 不同的平台执行不同的样式

    import { Platform, StyleSheet } from 'react-native';
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        ...Platform.select({                //不同的平台执行不同的样式
          ios: {
            backgroundColor: 'red',
          },
          android: {
            backgroundColor: 'blue',
          },
        }),
      },
    });
    
  • **再比如: ** 不同的平台选择不同的组件

      var Component = Platform.select({
          ios: () => require('ComponentIOS'),
          android: () => require('ComponentAndroid'),
        })();
    
      <Component />;
    

平台检测 Platform.OS

Platform.OSiOS上会返回ios,而在Android设备或模拟器上则会返回android

import { Platform, StyleSheet } from 'react-native';

var styles = StyleSheet.create({
  height: (Platform.OS === 'ios') ? 200 : 100,
});

检测安卓版本 Platform.Version

  import { Platform } from 'react-native';

  if(Platform.Version === 21){
    console.log('Running on Lollipop!');
  }

相关文章

网友评论

      本文标题:React- Native 特定平台扩展名, 及平台检测

      本文链接:https://www.haomeiwen.com/subject/zynqgttx.html