我收到一些包含 html 标签的字符串。示例:“您好,请点击此处” 我创建了一个函数来解释它们,目的是在本机反应下渲染它:
formating(text){
// Define regular expressions to match HTML tags
const boldRegex = /<b>(.*?)<\/b>/g;
const italicRegex = /<i>(.*?)<\/i>/g;
const underlineRegex = /<u>(.*?)<\/u>/g;
const lineBreakRegex = /<br\s?\/?>/g;
let formattedText = text
.replace(boldRegex, (_, content) => <Text style={{ fontWeight: 'bold' }}>{content}</Text>)
.replace(italicRegex, (_, content) => <Text style={{ fontStyle: 'italic' }}>{content}</Text>)
.replace(underlineRegex, (_, content) => <Text style={{ textDecorationLine: 'underline' }}>{content}</Text>)
.replace(lineBreakRegex, () => <Text>{'\n'}</Text>);
return <Text>{formattedText}</Text>
}
问题是当我在我的应用程序中显示它时:
<View>
{string.formating("my string")}
</View>
它呈现给我“你好,单击 [object Object]”
所以返回的内容可以很好地解释,问题来自于替换,但无法找到解决方案。
提前感谢您的帮助。
解决方案是使用reactStringReplace install 和yarn add react-string-replace。
这里是新代码:
formating(text) {
const replacements = [
{ regex: /<b>(.*?)<\/b>/g, component: (match, i) => <Text style={{ fontWeight: 'bold' }}>{match}</Text> },
{ regex: /<i>(.*?)<\/i>/g, component: (match, i) => <Text style={{ fontStyle: 'italic' }}>{match}</Text> },
{ regex: /<u>(.*?)<\/u>/g, component: (match, i) => <Text style={{ textDecorationLine: 'underline' }}>{match}</Text> },
{ regex: /<br\s?\/?>/g, component: (match, i) => <Text>{'\n'}</Text> }
];
let formattedText = text;
replacements.forEach(({ regex, component }) => {
formattedText = reactStringReplace(formattedText, regex, component);
});
return <Text>{formattedText}</Text>;
}
感谢@Wiktor Stribiżew 给了我这首歌。