I'm trying to create some reusable UI components for my React-Native app that have default styles.
An example 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 a way to do this? Obviously if I try to access this.props.style
it just returns an ID for a compiled stylesheet.
With React Native, you style your application using JavaScript. All of the core components accept a prop named style . The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g. backgroundColor rather than background-color .
I found a way to do it while browsing through the source code for React-Native-Router-Flux.
Stylesheets can be passed in as an array, and it looks like React-Native applies them in order from left to right (allowing you to overwrite specific properties).
Here is what the updated MyText
component should look 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>
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With