React Native 图片下方文本无法居中对齐问题求助
解决方案
你的问题由两个可快速修复的错误导致:
- 样式绑定属性拼写错误:
Text组件绑定样式的属性应该为style,你代码中多写了一个s写成styles,导致设置的alignSelf: 'center'完全没有生效。 - 内层容器缺少对齐规则:包裹
Image和Text的匿名View没有设置子元素对齐规则,宽度默认自适应父容器,也会导致对齐偏差。
修改后完整代码
import React from 'react' import { View, StyleSheet, Image, Text } from 'react-native' function RecentlyJoinedProfileCard({title, image}) { return ( <View style={styles.container}> {/* 给内层View增加样式 */} <View style={styles.innerCard}> <Image style={styles.image} source={{uri: image}} /> {/* 把styles改为style */} <Text style={styles.name}>{title}</Text> </View> </View> ); } const styles = StyleSheet.create({ container: { paddingBottom:55 }, // 新增内层容器样式,设置子元素居中、宽度和图片整体占宽一致 innerCard: { alignItems: 'center', width: 120 }, image: { width:100, height:100, borderRadius: 75, marginHorizontal:10, marginVertical:10 }, name: { fontSize: 15, fontWeight: "bold" } }) export default RecentlyJoinedProfileCard
修改后文字会自动在头像正下方居中展示,不需要额外给Text设置alignSelf属性,内层容器的alignItems: 'center'已经可以实现所有子元素居中对齐。
内容的提问来源于stack exchange,提问作者Gurmukh Singh
相关产品推荐
相关产品推荐

