React Native:用Text组件替换字符串



我正在尝试转换一些自制的标记/bbcode,为此,在某些情况下,我不需要返回字符串,而是需要返回文本组件,我正在尝试用这个小函数来实现这一点,但问题是,当我渲染它时,它显示的是[object object],而不是组件。

helper.js

import { Text } from "react-native";
const decodeTags = (string) => {
string = string.replace(
/[b](.+)[/b]/isu,
<Text style={{ fontWeight: "bold" }}>$1</Text>
);

profilBio.js

<Text style={styles.bio}>
{decodeTags(props.profil.bio)}
</Text>

渲染

[对象对象](而不是一些带有粗体部分的文本(

您需要一些预处理函数,它基本上会在需要加粗的字符串处拆分字符串。之后,只需对基本字符串substring进行操作并连接各部分。

例如:

const highlightKeyword = useCallback((originalString = '', searchQuery) => {
let s = originalString;
let searchStartIndex = s.indexOf(searchQuery);
return (
<Text>
<Text style={Styles.text}>{s.substr(0, searchStartIndex)}</Text>
<Text style={[Styles.text, {color: Colors.RED}]}>{searchQuery}</Text>
<Text style={Styles.text}>
{s.substr(searchStartIndex + searchQuery.length, s.length)}
</Text>
</Text>
);
}, []);
highlightKeyword(props.profil.bio,searchQuery)

如果请求是如何有条件地更新样式;

有条件地更新样式;

<Text style={(this.state.myCondition == true) ? styles.bio_font_weight : styles.bio}>{decodeTags(props.profil.bio)}</Text>

并更新decodeTags()以仅返回数据,而不返回Text组件。

最新更新