Merge / merge two or more different StyleSheet components in React Native?

I separate my styles as follows:

styles / |-- base.js |-- base.ios.js |-- base.android.js 

Each of them exports the StyleSheet component created in this example:

 import { StyleSheet } from 'react-native'; export default StyleSheet.create({ statusBar: { height: 20 }); 

How can I combine them, so I only have one base style object? I am looking for something like:

 const baseStyles = mergeStyles(baseStyle, platformStyle); 
+10
source share
3 answers

you are very close:

 const baseStyles = [baseStyle, platformStyle]; 

in principle, any component can cascade styles such styles:

 <View style={[styles.style1,styles.style2]}></View> 
+18
source

You can combine style sheets using the '...' distribution operator, warning that any variables with the same name will be overwritten by the last instance.

Here is a small demo application for demonstration:

 'use strict'; import React, { Component } from 'react'; import { Alert, Button, StyleSheet, Text, AppRegistry, View, } from 'react-native'; class listTest extends Component { render() { return ( <View style={styles3.myViewBox}> <Text style = {styles3.myTextBox1}> TEST </Text> </View> ); } } const styles = StyleSheet.create({ myTextBox1: { backgroundColor:'red', }, myViewBox: { backgroundColor:'blue', margin:15, padding:15, } }); const styles2 = StyleSheet.create({ myTextBox2: { backgroundColor:'yellow', }, myViewBox: { backgroundColor:'green', margin:15, padding:15, }, }); const styles3 = {...styles,...styles2}; AppRegistry.registerComponent('listTest', () => listTest); 

EDIT:

If you are using ES5, you can simply use:

const styles3 = Object.assign (styles, styles2);

+6
source

You can also use the StyleSheet.flatten method. See the documentation here .

 var styles = StyleSheet.create({ listItem: { flex: 1, fontSize: 16, color: 'white', }, selectedListItem: { color: 'green', }, }); StyleSheet.flatten([styles.listItem, styles.selectedListItem]); // returns { flex: 1, fontSize: 16, color: 'green' } 
0
source

Source: https://habr.com/ru/post/1013435/


All Articles