2016-04-13 48 views
8

我试图为具有默认样式的React-Native应用程序创建一些可重用的UI组件。如何将样式传递给React-Native中的容器组件

一个例子默认MyText(橙色,14,黑体):

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> 
    } 
} 

如何我想使用它:

import Text from '../ui/myText'; 

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

有没有办法做到这一点?很明显,如果我尝试访问this.props.style它只是返回编译样式表的ID。

回答

18

我在浏览React-Native-Router-Flux的源代码时发现了一种方法。

样式表可以作为数组传递,它看起来像React-Native按从左到右的顺序应用它们(允许您覆盖特定的属性)。

这里是更新MyText成分应该是什么样子:

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> 
    } 
} 
相关问题