一种简单的解决方案是使用反应本机解析文本 https://github.com/taskrabbit/react-native-parsed-text。
这是一个例子:
import * as React from "react";
import { Text, View, StyleSheet } from 'react-native';
import ParsedText from 'react-native-parsed-text';
const userNameRegEx = new RegExp(/@([\w\d.\-_]+)?/g);
export default class Example extends React.Component {
handleNamePress = (name) => {
alert("Pressed username " + name);
}
render() {
return (
<View style={styles.container}>
<ParsedText
style={styles.text}
parse={
[
{pattern: userNameRegEx, style: styles.username, onPress: this.handleNamePress},
]
}
childrenProps={{allowFontScaling: false}}
>
This is a text with @someone mentioned!
</ParsedText>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
color: 'black',
fontSize: 15,
},
username: {
color: 'white',
fontWeight: 'bold',
backgroundColor: "purple",
paddingHorizontal: 4,
paddingBottom: 2,
borderRadius: 4,
},
});
但是,该库不支持渲染自定义视图。上面的例子是通过纯粹的样式实现的。如果您需要自定义视图,您需要自己实现一些东西。很长一段时间以来,不可能渲染嵌入文本组件中的任意组件。然而,现在情况已经改变了,我们可以做这样的事情:
<Text>Hello I am an example <View style={{ height: 25, width: 25, backgroundColor: "blue"}}></View> with an arbitrary view!</Text>
在这里检查两个代码示例:https://snack.expo.io/@hannojg/restless-salsa https://snack.expo.io/@hannojg/restless-salsa
一个重要的注意事项:您可以渲染的输出ParsedText
或您自己的自定义组件TextInput
, 像这样:
<TextInput
...
>
<ParsedText
...
>
{inputValue}
</ParsedText>
</TextInput>