Pressable包裹Text组件后文本对齐偏移的原因及解决办法
问题原因
在React Native中,组件的嵌套子元素如果同为类型,会共享同一段文本排版上下文,自动遵循基线对齐规则。但
另外现有代码里还有一个功能缺陷:调用Linking.openURL()打开邮箱需要添加mailto:前缀,直接写邮箱地址无法正常唤起邮箱应用。
修复方案
方案1:直接使用Text的onPress属性(最推荐)
```return (<Text>本身自带onPress回调支持,不需要额外嵌套<Pressable>,完全保留文本排版特性,不会出现对齐问题。 代码示例: ```jsx <View style={{padding: 10}}> <Text> This is the body of my text <Text style={{color: 'blue'}} onPress={() => Linking.openURL('mailto:info@company.com')} > info@company.com </Text> )
方案2:保留Pressable时添加对齐样式
如果需要使用Pressable的按下状态、自定义点击反馈等能力,给Pressable添加alignSelf: 'baseline'属性,同时保证内外Text的lineHeight一致,移除Pressable默认的上下内边距即可。
代码示例:
<View style={{padding: 10}}> <Text style={{lineHeight: 20}}> This is the body of my text <Pressable onPress={() => Linking.openURL('mailto:info@company.com')} style={{alignSelf: 'baseline', paddingVertical: 0}} > <Text style={{color: 'blue', lineHeight: 20}}> info@company.com</Text> </Pressable> </Text> </View>
内容的提问来源于stack exchange,提问作者JaeLeeSo
相关产品推荐
相关产品推荐

