返回后反应原生显示[object Object]

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

我收到一些包含 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]”

所以返回的内容可以很好地解释,问题来自于替换,但无法找到解决方案。

提前感谢您的帮助。

javascript regex react-native replace jsx
1个回答
0
投票

解决方案是使用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 给了我这首歌。

© www.soinside.com 2019 - 2024. All rights reserved.