我們使用 React Native ,需要根據(jù)代碼在不同的平臺上運行洁闰,應用不同的樣式歉甚。可以通過改造React Native StyleSheet API的方式扑眉。
import { StyleSheet, Platform } from 'react-native';
function create(styles) {
const platformStyles = {};
Object.keys(styles).forEach((name) => {
const { ios, android, ...style } = styles[name];
let xeStyle = style;
if (ios && Platform.OS === 'ios') {
xeStyle = { ...style, ...ios };
}
if (android && Platform.OS === 'android') {
xeStyle = { ...style, ...android };
}
platformStyles[name] = xeStyle;
});
const result = StyleSheet.create(platformStyles);
return result;
}
export default {
...StyleSheet,
create,
};
通過以上代碼改造完成后纸泄,引入使用:
import StyleSheet from '../../utils/rzStyleSheet';
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#000',
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
ios: {
top: 64,
},
android: {
top: 44,
},
},
});