最近一个需求是支持Text 组件中的文字可选中,看起来挺简单的。

可以使用selectable 属性来实现
<Text selectable>文字</Text>
但当我添加这个属性后,确发现只要添加后的第一次文本可选中,当页面刷新后就不行了。查了一会咋github 找到一个方法,如果是<FlatList>
或 <List>
组件中使用了Text 逐渐,需要添加属性:
<FlatList removeClippedSubviews={false}/> // 但list 内的文本选中还是不是很灵敏,甚至偶尔选不中
添加后看着正常了,但如果是在list 中长按选中文字,会触发跳转详情页,所以还需要兼容。
import React, { useState } from 'react'; import { View, Text, Pressable } from 'react-native'; const MyComponent = ({ navigation, post }) => { const [isLongPress, setIsLongPress] = useState(false); const handleGoToDetail = () => { if (!isLongPress) { navigation.push(Screen.POST, { id: post._id, post: toJS(post), }); } }; const handleLongPress = () => { setIsLongPress(true); }; const handlePressOut = () => { setIsLongPress(false); }; return ( <Pressable onPress={handleGoToDetail} onLongPress={handleLongPress} onPressOut={handlePressOut}> <View> <Text>Selectable Text</Text> </View> </Pressable> ); }; export default MyComponent;
一切正常之后,我感觉默认的选中文字的颜色比较难看,并且和我们主题色不太搭,想修改一下。
<Text selectable selectionColor="red">文字</Text>

确发现,修改完之后,是选中的部分颜色变了,”文本选择手柄”(Text Selection Handles)并没有改变颜色,问了下 GPT 说 RN 不支持修改,除非自己实现。
github 上也找到了类似的issue,说是在安卓上手柄颜色不会跟着变。

github 上还查到一个新增属性selectionHandleColor,但我试了不生效。
后来想通过修改Android 的主题色来覆盖,颜色能生效。
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> <!-- Customize your theme here. --> <item name="android:colorAccent">@color/app_color_red</item> <item name="android:colorControlActivated">@color/app_color_red</item> </style> </resources>