仿抖音 以#开头的字符串 判定为话题标签 并展示为蓝色

2023-05-10  本文已影响0人  wustzhy

需求:


屏幕录制.gif
image.png
image.png

调研:
iOS的TextField可以设定attributedString富文本,但RN的TextInput是不具备的。

方案:
TextInput上浮一个style大小一致的Text,TextInput文字颜色设为透明,Text内嵌套 style为蓝色的Text 用来展示#任意(至少1个)字符

代码

import React, { useState } from 'react';
import { View, TextInput, Text, StyleSheet } from 'react-native';

const App = () => {
  const [text, setText] = useState('');

  const handleTextChange = (inputText) => {

    // 检测输入字符串中是否包含 "#"
    if (inputText.includes('#')) {
      // 将包含 "#任意(至少1个)字符" 的部分替换为带有蓝色样式的文本组件
      const parts = inputText.split(/(?=#|\s)/g);
      console.log('parts: ', parts);
      const formattedText = parts.map((part, index) => {
        return (
          <Text key={index} style={(part.includes('#') && part.length > 1 ? { color: 'blue' } : {})}>
            {part}
          </Text>
        );
      });

      // 设置更新后的文本
      setText(formattedText);
    } else {
      // 输入字符串不包含 "#文字",直接设置文本
      setText(inputText);
    }
  };

  return (
    <View style={{ flex: 1, backgroundColor: 'pink', marginTop: 100 }}>
      <TextInput
        style={[styles.text, { borderWidth: 1, borderColor: 'gray', width: '100%', padding: 0, color: 'rgba(0,0,0,0)' }]}
        onChangeText={handleTextChange}
        multiline={true}
      >
        <Text style={{ color: 'yellow'}}>{text}</Text>
      </TextInput>
    </View>
  );
};

const styles = StyleSheet.create({

  container: {
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: 'gray',
    padding: 10,
    marginTop: 20,
  },
  text: {
    fontSize: 16,
    lineHeight: 20
  },
});


export default App;

上一篇下一篇

猜你喜欢

热点阅读