1. 程式人生 > 實用技巧 >react-native TextInput輸入框輸入時關鍵字高亮

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: { width: '90%', height: 24, position: 'relative', alignSelf:
'center', }, inputWrapper: { position: 'absolute', top: 0, height: 24, width: '100%', borderWidth: 1, borderColor: 'gray', }, input: { height: 24, fontSize: 18, width: '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