是否可以在不使用外部库的情况下,解析带有标签的字符串,然后使用 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>
)
}
我得到的是:
Let's [object Object] on [object Object]
参见示例:https://codesandbox.io/s/react-native-69dwm?fontsize=14
有没有办法在 jsx 中实现这一点?谢谢。
最佳答案
不能这样使用反向引用,需要动态求值的时候可以使用replace的回调函数
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"))
要解决您的特定问题,您需要通过拆分字符串然后根据值构建文本组件来解决它
const HASHTAG_FORMATTER = string => {
return string.split(/((?:^|\s)(?:#[a-z\d-]+))/gi).filter(Boolean).map((v,i)=>{
if(v.includes('#')){
return <Text key={i} style={{color:'green'}}>{v}</Text>
} else{
return <Text key={i}>{v}</Text>
}
})
};
关于javascript - 在 React Native 中创建一个简单的标签格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387327/