2016-12-29 28 views
1

我已經擴展了Text組件,以便具有可自定義字體的可重用的文本組件。將樣式應用於擴展React Native組件的建議方式是什麼?

我的自定義組件應接受傳遞給它的樣式並向其中添加自定義字體。

目前,我正在做這個:

MyText.js

import React from 'react' 
import { 
    Text, 
    StyleSheet 
} from 'react-native'; 


export default class MyText extends React.Component { 

    render() { 

     const style = 
      Object.assign({}, 
       StyleSheet.flatten(this.props.style), 
       {fontFamily: "My Font"} 
      ); 

     return (
      <Text style={style}> 
       {this.props.children} 
      </Text> 
     ); 
    } 

} 

雖然這正常工作,具有扁平化樣式表,每次似乎是錯誤的。以上是一個簡單的例子,我可以想到其他可以使用這種模式的組件。出於這個原因,我想確保我不會忽視更合適的方法。

+0

您可以爲組件提供樣式數組。所以你的情況下,以下將工作:''你的customStyle會覆蓋樣式對象上的現有鍵,如果你不想要把customStyle作爲數組的第一項。 – cubbuk

回答

1

那麼這取決於你想要自定義多少。在這種情況下,如果它只是一個不同的字體,它可能類似於

import React from 'react' 
import { 
    Text, 
    StyleSheet 
} from 'react-native'; 
import _ from 'lodash'; 



export default class MyText extends React.Component { 

    render() { 
     const filteredProps = _.omit(this.props, 'style'); 
     return (
      <Text style={[{fontFamily: "My Font"}, this.props.style]} {...filteredProps} /> 
     ); 
    } 

} 
相關問題