Rich ReactNative TextInput
Any way to create a "rich" TextInput in React Native? Maybe not a full blown wysiwyg, but maybe just change the text color of various pieces of text; like the @mention feature on Twitter or Facebook.
解决方案是,你可以像这样在<TextInput>
使用<Text>
元素作为子元素:
<TextInput>
whoa no way <Text style={{color:'red'}}>rawr</Text>
</TextInput>
Have a look at the TokenizedTextExample from the react-native docs. I think that'll get you close to what you're looking to do. The relevant code follows:
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>
);
}
}
You will have to use regex in order to achieve that behaviour. Someone has already created package for that have a look at react-native-parsed-text
This library allows you to parse a text and extract parts using a RegExp or predefined patterns. Currently there are 3 predefined types: url, phone and email.
Example from their 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>
链接地址: http://www.djcxy.com/p/92244.html