react-native TextInput输入框输入时关键字高亮

1.逻辑:

输入框本来是不会允许我们去将部分文字加上高亮,可以加高亮的是Text,我们只需将textInput里面的文字获取到,在把它们放到text当中,在让Text悬挂在TextInput上即可

2.代码

import React from 'react';
import { View, Text, TextInput, StyleSheet } from
'react-native'; const styles = StyleSheet.create({ wrapper: { '90%', height: 24, position: 'relative', alignSelf: 'center', }, inputWrapper: { position: 'absolute', top: 0, height: 24, '100%', borderWidth: 1, borderColor: 'gray', }, input: { height: 24, fontSize: 18, '100%', }, text: { height: 24, fontSize: 18, position: 'absolute', top: 0, color: 'transparent', }, mention: { backgroundColor: 'rgba(0, 150, 255, .5)', } }); export default class App extends React.Component { state = { inputText: '', formattedText: '', } handleChangeText = (inputText) => { const words = inputText.split(' ');
   const mentionKey = ['A', 'B', 'C'] const formattedText
= []; words.forEach(word => { if (!mentionKey.includes(word)) return formattedText.push(word, ' '); const mention = ( <Text key={word} style={styles.mention}> {word} </Text> ); formattedText.push(mention, ' '); }); this.setState({ inputText, formattedText }); } render() { return ( <View style={{ marginTop: 48 }}> <View style={styles.wrapper}> <Text style={styles.text}> {this.state.formattedText} </Text> <View style={styles.inputWrapper}> <TextInput style={styles.input} value={this.state.inputText} onChangeText={this.handleChangeText} /> </View> </View> </View> ); } }

3.效果

类似于插件: https://github.com/harshq/react-native-mentions  

原文地址:https://www.cnblogs.com/guan-shan/p/14074687.html