我正在尝试使用 React Native 在应用程序上呈现文本内容。文本内容是从服务器加载的。除了内容本身之外,网络响应还告诉我那些应该以不同颜色呈现的单词索引。
例如:
// from the response JSON, I can tell:
contentString='How can we dynamic render text in multiple colors?'
index=[1, 3, 5]
我需要在应用程序上将 contentString
渲染为黑色,并渲染 can
(index 1)、dynamic
(index 3) 和 文本(索引5)
为黄色。
我对此做了一些研究,我注意到“嵌套文本”将是一个解决方案。喜欢:
<Text style={{color: 'black'}}>
how
<Text style={{color: 'yellow'}}>
can
</Text>
we
<Text style={{color: 'yellow'}}>
dynamic
</Text>
.......
</Text>
索引数组因每个请求而异。我尽力编写一个函数来支持这种动态多色渲染,但没有运气。我还在学习算法,这个函数似乎太有挑战性了..
有人能解释一下吗?非常感谢!
最佳答案
你可以做这样的事情..
<Text style={{color: 'black'}}>
{contentString.split(" ").map((x, ind) =>
<Text style={{color: index.includes(ind)?'black':'yellow'}}>
{x+ " "}
</Text>)
}
</Text>
关于javascript - react native : Dynamically print Text in multiple color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56910600/