是否有可能在不使用外部库的情况下,使用#标签解析字符串,然后使用Text
组件设置其样式?
const string = "Let's #Tweet on #Twitter";
// Expect:
// Let's <Text style={{ color: 'blue' }}>#Tweet</Text> on <Text style={{ color: 'blue' }}>#Twitter</Text>
我以为这样可以:
import React from 'react';
import { Text } from 'react-native';
export const HASHTAG_FORMATTER = string => {
return string.replace(/(^|\s)(#[a-z\d-]+)/ig, `$1${<Text style={{ color: 'blue' }}>$2</Text>}`);
}
用法:
import React from 'react';
import { View, Text } from 'react-native';
import { HASHTAG_FORMATTER } from '../../utilities/hashtag';
const Home = props => {
return (
<View>
<Text>{HASHTAG_FORMATTER("Let's #Tweet on #Twitter")}</Text>
<View>
)
}
我得到的是:
让我们[对象对象]上的[对象对象]
请参见示例:https://codesandbox.io/s/react-native-69dwm?fontsize=14
是否有一种方法可以在jsx中实现?谢谢。
const HASHTAG_FORMATTER = string => {
return string.replace(/(^|\s)(#[a-z\d-]+)/ig, (m, g1, g2) => {
return g1 + "<span style={color:'green'}>" + g2 + "< /span>"
});
}
console.log(HASHTAG_FORMATTER("#tweet"))