【问题标题】:react-native: multi color text viewreact-native:多色文本视图
【发布时间】:2021-11-07 07:11:22
【问题描述】:

我想渲染一行文本,其中一些单词以不同的颜色突出显示。

理想情况下,我会使用带有 react 的 span 标签来实现。

想知道我如何对 react-native 做同样的事情?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    您可以通过使用嵌套的文本组件来实现此目的

    <Text style={{color: 'blue'}}>
        I am blue
        <Text style={{color: 'red'}}>
            i am red
        </Text>
        and i am blue again
    </Text>
    

    这里有一个link 来更好地解释它的文档

    【讨论】:

    • 如果你有动态文本怎么办?想象一下来自服务器的文本,带有一些占位符,表示客户端应该突出显示。
    • 这个很具体,所以默认不提供。不过实现起来应该不难。尝试编写一个特定的函数来解析来自服务器的字符串并输出一个对象,该对象包含要应用于每个子字符串的样式。然后,您可以将此对象提供给一个自定义组件,该组件呈现嵌套的 Text 组件,如上述。
    • 是的。这是有道理的。
    【解决方案2】:

    你可以做得更好,我的方式:

    CText = (props) => <Text style={{color: props.color}}>{props.children}</Text>
    

    内部渲染添加:

    const CText = this.CText
    

    然后返回

    <Text>I am <CText color={'red'}>Blue color</CText> and <CText color={'blue'}>Blue color</CText></Text>
    

    【讨论】:

      【解决方案3】:

      简单嵌套&lt;Text&gt;元素

      <Text>
          I am some text with 
          <Text style={{fontWeight: 'bold'}}>bold</Text> 
          stuff
      <Text>
      

      【讨论】:

        猜你喜欢
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 1970-01-01
        • 2016-03-08
        • 1970-01-01
        • 2018-01-26
        • 2021-05-23
        相关资源
        最近更新 更多