在React Native中创建"富"TextInput的任何方法?也许不是一个完整的wysiwyg,但也许只是改变各种文字的文字颜色; 喜欢Twitter或Facebook上的@mention功能.
解决方案是你可以像这样使用<Text>元素作为子元素<TextInput>:
<TextInput>
whoa no way <Text style={{color:'red'}}>rawr</Text>
</TextInput>
Run Code Online (Sandbox Code Playgroud)
小智 9
这个问题是不久前提出的,但我认为我的回答可以帮助其他人寻找如何为字符串的 @mention 部分着色。我不确定我这样做的方式是干净的还是“反应”的方式,但我是这样做的:我取输入的字符串并将其拆分为空白作为分隔符。然后我遍历数组,如果当前项与@mention/@user 的模式匹配,则将其替换为应用了样式的 Text 标记;否则返回项目。最后,我在 TextInput 元素内呈现 inputText 数组(包含字符串和 jsx 元素)。希望这可以帮助!
render() {
let inputText = this.state.content;
if (inputText){
inputText = inputText.split(/(\s)/g).map((item, i) => {
if (/@[a-zA-Z0-9]+/g.test(item)){
return <Text key={i} style={{color: 'green'}}>{item}</Text>;
}
return item;
})
return <TextInput>{inputText}</TextInput>
Run Code Online (Sandbox Code Playgroud)
您必须使用正则表达式才能实现该行为。有人已经为此创建了包,看看react-native-parsed-text
该库允许您使用 RegExp 或预定义模式解析文本并提取部分。目前有 3 种预定义类型:url、电话和电子邮件。
来自他们 github 的示例
<ParsedText
style={styles.text}
parse={
[
{type: 'url', style: styles.url, onPress: this.handleUrlPress},
{type: 'phone', style: styles.phone, onPress: this.handlePhonePress},
{type: 'email', style: styles.email, onPress: this.handleEmailPress},
{pattern: /Bob|David/, style: styles.name, onPress: this.handleNamePress},
{pattern: /\[(@[^:]+):([^\]]+)\]/i, style: styles.username, onPress: this.handleNamePress, renderText: this.renderText},
{pattern: /42/, style: styles.magicNumber},
{pattern: /#(\w+)/, style: styles.hashTag},
]
}
>
Hello this is an example of the ParsedText, links like http://www.google.com or http://www.facebook.com are clickable and phone number 444-555-6666 can call too.
But you can also do more with this package, for example Bob will change style and David too. foo@gmail.com
And the magic number is 42!
#react #react-native
</ParsedText>
Run Code Online (Sandbox Code Playgroud)
小智 6
查看react-native 文档中的TokenizedTextExample。我认为这会让你接近你想要做的事情。相关代码如下:
class TokenizedTextExample extends React.Component {
state: any;
constructor(props) {
super(props);
this.state = {text: 'Hello #World'};
}
render() {
//define delimiter
let delimiter = /\s+/;
//split string
let _text = this.state.text;
let token, index, parts = [];
while (_text) {
delimiter.lastIndex = 0;
token = delimiter.exec(_text);
if (token === null) {
break;
}
index = token.index;
if (token[0].length === 0) {
index = 1;
}
parts.push(_text.substr(0, index));
parts.push(token[0]);
index = index + token[0].length;
_text = _text.slice(index);
}
parts.push(_text);
//highlight hashtags
parts = parts.map((text) => {
if (/^#/.test(text)) {
return <Text key={text} style={styles.hashtag}>{text}</Text>;
} else {
return text;
}
});
return (
<View>
<TextInput
multiline={true}
style={styles.multiline}
onChangeText={(text) => {
this.setState({text});
}}>
<Text>{parts}</Text>
</TextInput>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3346 次 |
| 最近记录: |