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中的常量失效,需要在使用時按上面的方法重新定義