How can you pass styles through a container component in React-Native

I am trying to create some reusable user interface components for my React-Native application that have default styles.

Default MyText (orange, 14, bold):

 import React, { Component, StyleSheet, Text } from 'react-native'; const styles = StyleSheet.create({text: {color: 'orange', fontSize: 14, fontWeight: 'bold'}}); export default class MyText extends Component { render() { return <Text style={styles.text}>{this.props.children}</Text> } } 

How I would like to use it:

 import Text from '../ui/myText'; ... <Text style={{color: 'black'}}>My custom styled text, but in black instead of orange</Text> ... 

Is there any way to do this? Obviously, if I try to access this.props.style , it will simply return the identifier for the compiled stylesheet.

+8
react-native
source share
1 answer

I found a way to do this by looking at the source code for React-Native-Router-Flux.

Style sheets can be passed as an array, and it seems that React-Native applies them in order from left to right (allowing you to rewrite certain properties).

Here's what the updated MyText component looks like:

 import React, { Component, StyleSheet, Text } from 'react-native'; const styles = StyleSheet.create({text: {color: 'orange', fontSize: 14, fontWeight: 'bold'}}); export default class MyText extends Component { render() { return <Text style={[styles.text, this.props.style]}>{this.props.children}</Text> } } 
+18
source share

All Articles