2016-08-17 192 views
4

我想将文本样式设置为React Native中的上标。这将如何完成?有没有一种方法可以使用Javascript sup()字符串方法在<Text>对象内返回字符串作为上标?React Native中的上标文本

回答

0

Javascripts sub()功能只会围绕您的文字与<sub></sub>标签,它们被识别为RN中的文字。您将需要建立自己的功能,如:

export default class Test extends Component { 
    sub = (base, exponent) => { 
     return <View style={{flexDirection: 'row'}}> 
      <View style={{alignItems: 'flex-end'}}> 
       <Text style={{fontSize: 13}}>{base}</Text> 
      </View> 
      <View style={{alignItems: 'flex-start'}}> 
       <Text style={{fontSize: 10}}>{exponent}</Text> 
      </View> 
     </View> 
    } 

    render() { 
     return(
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> 
       <Text>{(() => 'hello'+'world'.sub())()}</Text> 
       {(() => this.sub('hello','world'))()} 
       {(() => this.sub('2','6'))()} 
      </View> 
     ); 
    } 
} 

Result in iOS Simulator

+0

当我将它包含在现有的'View'中时出现错误:“嵌套在中的视图必须具有宽度和高度” –

+0

另外,从React Native文档中,在'Text'内嵌入'View'将会起作用仅限iOS。不是跨平台的。 –

+0

这是正确的,但如果你在Android上,你可以简单地使用'textAlignVertical:'top'' – Fabian

0

我发现这个问题的最好方法是不理想,但它跨平台工作。我需要上标的字符是默认情况下某些字体已上标的字符。所以,我只是将一个类似的字体家族与superscripted®包含在一起,就像魔术一样。

3

只需使用fontSize的,lineHeight是,textAlignVertical:

<Text style={{fontSize:20, lineHeight:22}}> 
    foo 
    <Text style={{fontSize:20 * 1.6, lineHeight:22 * 1.1, textAlignVertical: 'top'}}> 
    bar 
    </Text> 
</Text> 
+0

我需要修复,因为lineHeights –

+0

textAlignVertical之间的特殊长宽比需要是仅限android! – Max

5

我得到这个使用视图容器和Flex为我工作。

<View style={{flexDirection: 'row', alignItems: 'flex-start'}}> 
    <Text style={{fontSize: 20, lineHeight: 30}}>10</Text> 
    <Text style={{fontSize: 11, lineHeight: 18}}>am</Text> 
</View> 

这里是链接到这个动作https://repl.it/Haap/0

干杯!

相关问题