React Native 中為IOS和Android設定不同的Style樣式,一套程式碼解決雙端顯示
阿新 • • 發佈:2018-11-09
React Native 開發中,大多數的元件都是IOS和Android通用的,包括大量的功能性程式碼,至少有80%以上的程式碼可以複用,而剩下的一些元件樣式/少量的程式碼會需要區分雙端,但是為了這少量的程式碼把IOS和Android完全區分這明顯不合適,程式碼複用性下降,程式碼維護量上升,明顯是不合理的。
本文借鑑網上的教程,為大家介紹如何為IOS端和Android端設定不同的style樣式,讓一套程式碼雙端適用。本文僅解決部分元件的style樣式,後期如果遇到其它的程式碼型別也會為大家提供教程。
React Native 版本:`0.55.4`,因為0.56版RN在Window端報錯,所以Mac也習慣使用0.55.4
由於IOS的螢幕設定,IOS端一般需要設定一個marginTop:20的屬性,而android是不需要的,這裡以此為例
實現原理:重定義RN自帶的StyleSheet元件中的create方法,新增IOS和android判斷。
步驟一、新建一個StyleSheet.js檔案,輸入以下程式碼
import {StyleSheet, Platform} from 'react-native'; export function create(styles: Object): {[name: string]: number} { const platformStyles = {}; Object.keys(styles).forEach((name) => { let {ios, android, ...style} = {...styles[name]}; if (ios && Platform.OS === 'ios') { style = {...style, ...ios}; } if (android && Platform.OS === 'android') { style = {...style, ...android}; } platformStyles[name] = style; }); return StyleSheet.create(platformStyles); }
步驟二,檢視頁面取消RN中StyleSheet的呼叫,新增自定義的StyleSheet
import React, { Component } from 'react'; import { Text, View} from 'react-native';/*/這裡不再引入StyleSheet*/ /*引入自定義的StyleSheet檔案,假設上面定義的檔案與當前檔案在同一目錄下*/ const StyleSheet = require('./StyleSheet'); const styles = StyleSheet.create({ container:{ flex:1, alignItems:'center', justifyContent:'center', ios:{ marginTop:20, backgroundColor:'red', } android:{ backgroundColor:'blue', } } }); export default class HomeView extends Component<Props> { render( return ( <View style={styles.container}> <Text>請自行檢視效果</Text> </View> ) ) }
圖片就不放了,請自行測試效果
注:本文方法會導致StyleSheet中的常量失效,需要在使用時按上面的方法重新定義