Rich ReactNative TextInput

任何方式在React Native中创建“丰富”的TextInput? 也许不是一个完整的wysiwyg,但也许只是改变各种文本的文本颜色; 就像Twitter或Facebook上的@mention功能一样。


解决方案是,你可以像这样在<TextInput>使用<Text>元素作为子元素:

<TextInput>
    whoa no way <Text style={{color:'red'}}>rawr</Text>
</TextInput>

看看来自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>
    );
  }
}

你将不得不使用正则表达式来实现这种行为。 有人已经创建了一个包,看看react-native-parsed-text

该库允许您解析文本并使用RegExp或预定义模式提取零件。 目前有3种预定义类型:网址,电话和电子邮件。

来自他们的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/92243.html

上一篇: Rich ReactNative TextInput

下一篇: Why are git submodules incompatible with svn externals?