如何在react-native中将组件呈现为文本

问题描述 投票:0回答:2

有人可以帮助我从函数中的组件渲染Text吗?这是我的情况。我有一个功能来强调字符串中的自定义字符。功能是这样的。

 highlight = (string) => {
    var re = new RegExp('ABC', 'g')
    var result = string.replace(re, <Text style={{ fontWeight : 'bold' }}>ABC</Text>)
    return(
        <Text>{result}</Text>
    )
}

然后,在我的类的渲染函数中,我这样调用这个函数:

 <Text style={{marginBottom: 10}}>
    {this.highlight('ABC DEF GHI')}
 </Text>

目标是,我想从ABC给出大胆的ABC DEF GHI。但是当我运行它时,结果是这样的:[object Object] DEF GHI ..有人可以帮助我,结果是ABC DEF GHI

reactjs react-native
2个回答
3
投票

单词总是用空格分隔?如果是这样,我会做这样的解决方案:

{
  'ABC DEF GHI'.split(" ").map(
      s => s.match('ABC', 'g') ? 
        <Text style={{ fontWeight : 'bold' }}>{s}</Text> : 
        <Text>{s}</Text>)
 }

1
投票

[object Object]实际上是由代码中的这一行引起的错误语句

 var result = string.replace(re, <Text style={{ fontWeight : 'bold' }}>ABC</Text>)

现在你的结果变量和对象变为string.replace(re,<Text style={{ fontWeight : 'bold' }}>ABC</Text>)返回错误。 这是因为替换的第二个参数必须是字符串否则会产生意外的令牌...错误。 解决这个问题你可以做到这一点

  highlight = (string) => {
    var boldString = "ABC"
    var re = new RegExp(boldString, 'g')
    var result = string.replace(re,"")
    return{
        boldText:boldString,
        regularText:result
     }

}

并在你的渲染功能

<Text style={{marginBottom: 10}}>
    <Text style={{ fontWeight : 'bold' }}>{this.highlight("ABC DEF GHI").boldText}</Text>
    {this.highlight('ABC DEF GHI').regularText}
 </Text>
© www.soinside.com 2019 - 2024. All rights reserved.