有没有办法在TextInput内部呈现组件?

时间:2019-06-21 06:45:28

标签: javascript react-native

我正在尝试在TextInput上呈现@提及,我尝试将所需的组件和文本作为数组传递给TextInput。

它可以工作,但是一旦输入更改,提及内容就会转换为纯文本。有什么方法可以保留渲染的组件并防止将其转换为纯文本?

代码:

  renderMessageWithMentions = (messageText: string) => {
    const mentionsRegExp = /<@(.*?)>/g;
    const mentionUIDs = R.match(mentionsRegExp, messageText).map(mention => {
      let filteredStr = mention.replace(/<@/g, "");
      filteredStr = filteredStr.replace(/>/g, "");
      return filteredStr;
    });

    return R.map(text => {
      if (mentionUIDs.includes(text)) {
        return <Mention uid={text} />;
      }

      return text;
    }, R.split(mentionsRegExp, messageText));
  };

提及的格式如下<@UID>。在这里,我遍历messageText,如果提到它,我将返回Mention组件,该组件将以蓝色文本呈现用户的名称,否则返回纯文本。

这就是我要渲染的:

  setText = text => {
    const { isTrackingStarted, previousChar } = this.state;
    const lastChar = text.substr(text.length - 1);
    const wordBoundry = R.trim(previousChar).length === 0;

    if (lastChar === "@" && wordBoundry) {
      this.startTracking();
    } else if ((lastChar === " " && isTrackingStarted) || text === "") {
      this.stopTracking();
    }

    this.setState({ text, previousChar: lastChar });
  };

<TextInput onChangeText={this.setText}>
  {this.renderMessageWithMentions(messageText)}
</TextInput>

Image: Before changing text

Image: After changing text

0 个答案:

没有答案