[英]How to render component as text in react-native
有人可以帮助我从功能组件中渲染文本吗? 这是我的情况。 我有一个功能来突出显示字符串中的自定义字符。 功能是这样的。
highlight = (string) => {
var re = new RegExp('ABC', 'g')
var result = string.replace(re, <Text style={{ fontWeight : 'bold' }}>ABC</Text>)
return(
<Text>{result}</Text>
)
}
然后,在我的类的render函数中,我这样调用此函数:
<Text style={{marginBottom: 10}}>
{this.highlight('ABC DEF GHI')}
</Text>
我的目标是给ABC DEF GHI
大胆的ABC
。 但是当我运行此命令时,结果是这样的:[object Object] DEF GHI ..有人可以帮助我,所以结果是ABC DEF GHI
单词将始终由空格分隔吗? 如果是这样,我会做一个这样的解决方案:
{
'ABC DEF GHI'.split(" ").map(
s => s.match('ABC', 'g') ?
<Text style={{ fontWeight : 'bold' }}>{s}</Text> :
<Text>{s}</Text>)
}
[object Object]实际上是由您的代码中的这一行引起的错误语句
var result = string.replace(re, <Text style={{ fontWeight : 'bold' }}>ABC</Text>)
现在,您的结果变量变为并且对象为string.replace(re, <Text style={{ fontWeight : 'bold' }}>ABC</Text>
)返回错误。
这是因为replace的第二个参数必须是字符串,否则会产生意外的令牌...错误。
解决这个问题
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.