Merge / Combine two or more different StyleSheet components in React Native?
you are very close:
const baseStyles = [baseStyle, platformStyle];
basically any component can cascade styles like this:
<View style={[styles.style1,styles.style2]}></View>
You can combine style sheets using the spread operator '...', be warned that any variables of the same name will be overwritten by the last instance.
Heres a small demo app to demonstrate:
'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're running ES5 you can just use:
const styles3 = Object.assign(styles,styles2);
You can also use StyleSheet.flatten
method. See 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' }
UPDATE:
StyleSheet.flatten
internally uses StyleSheetRegistry.getStyleByID(style) to resolve style objects represented by IDs. IDs enable optimizations through the bridge and memory in general. Referring to style objects directly will deprive you of these optimizations.
So flatten method is better than style={ [ styles.listItem, styles.selectedListItem ] }