【问题标题】:Superscript Text in React NativeReact Native 中的上标文本
【发布时间】:2016-08-17 17:09:58
【问题描述】:

我想在 React Native 中将文本样式设置为上标。这将如何实现?有没有办法利用 Javascript sup() 字符串方法在 <Text> 对象中将字符串作为上标返回?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我使用视图容器和 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

    干杯!

    【讨论】:

    【解决方案2】:

    只需使用 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>
    

    【讨论】:

    • 我需要修复,因为 lineHeights 之间需要特殊的纵横比
    • textAlignVertical 仅适用于安卓系统!
    【解决方案3】:

    我这样做只是为了实现上标

     <View style={{ flexDirection: 'row' }}>
      <Text style={{ fontSize: 30 }}>e</Text>
      <Text style={{ fontSize: 10 }}>x</Text>
     </View>
    

    【讨论】:

    • 不过,“x”需要位于“e”上方。
    【解决方案4】:

    Javascripts sub() 函数只会用 &lt;sub&gt;&lt;/sub&gt; 标签包围您的文本,并且它们在 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>
            );
        }
    }
    

    【讨论】:

    • 当我将它包含在现有的 View 中时出现错误:“嵌套在 中的视图必须具有宽度和高度”
    • 另外,根据 React Native 文档,在 Text 中嵌入 View 仅适用于 iOS。不是跨平台的。
    • 没错,但如果你使用的是安卓系统,你可以简单地使用textAlignVertical: 'top'
    • 我认为现在(如果你想使用文本 + 嵌套指数)你必须做非常丑陋的视图和文本元素的混合。也许看看productpains 有一个投票系统来支持未来的功能。我添加了指向 CSS vertical align property page 的链接,并引用了 sub/super 属性。
    • 在 Android 上,我尝试了 textAlignVertical: 'top' 属性,如下所示:&lt;Text&gt;Productname&lt;Text style={{fontSize: 9, textAlignVertical: 'top'}}&gt;®&lt;/Text&gt;&lt;/Text&gt; 无济于事。有什么想法吗?
    【解决方案5】:

    我为这个问题找到的最佳方法并不理想,但它可以跨平台工作。我需要上标的字符是某些字体默认上标的®。所以,我只是简单地在上标 ® 中加入了一个类似的字体系列,它就像魔术一样工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多