首页 > 解决方案 > 加粗文本中的特定单词 - React Native?

问题描述

我需要替换 boldTextbased on the index value的地方,{index}那个词应该是粗体

例子:

 {
  sentence: {0} and {1} are great
  boldText: ['You', 'Your Family']
 }

输出:

你的家人都很棒。

标签: javascriptreactjsreact-native

解决方案


这是一个简单的例子。

希望对您有所帮助!

const sample = {
  sentence: '{0} and {1} are great',
  boldText: ['You', 'Your Family']
};

const applyBoldStyle = text => text.sentence.replace(/\{(\d+)\}/g, (match, i) => `<b>${text.boldText[i]}</b>`);

console.log(applyBoldStyle(sample));

请注意,你可以传递任何你想适合 react-native 的东西。这里我传递带有<b>标签的简单 HTML,这里重要的是replace函数。让它返回你想要的任何东西。

使用 react-native,您可能希望使用以下内容:

const sample = {
  sentence: '{0} and {1} are great',
  boldText: ['You', 'Your Family']
};

const applyBoldStyle = text => {
  let numberOfItemsAdded = 0;
  const result = text.sentence.split(/\{\d+\}/);
  text.boldText.forEach((boldText, i) => result.splice(++numberOfItemsAdded + i, 0, <Text style={{fontWeight: 'bold'}}>{boldText}</Text>););
  return <Text>{result}</Text>;
};

推荐阅读