React Native中View设置阴影边框后内部Text带阴影,如何仅保留边框阴影?
问题原因
这是iOS端React Native的默认特性:父级View设置的shadow*系列属性会被内部所有Text组件继承,安卓端无此问题。
解决方案
你可以根据实际开发场景选择以下两种方案:
- 方案1:给Text组件单独添加阴影清除样式,覆盖父级继承的效果,适合内部仅存在少量Text的场景,改动成本最低
<View style={styles.reviewBox}> <Text style={{ fontSize: 14, color: 'black', // 新增样式清除继承的阴影 shadowColor: 'transparent', shadowOpacity: 0, shadowRadius: 0, shadowOffset: { width: 0, height: 0 } }}> Why does this text have shadows on it </Text> </View>
- 方案2:拆分布局结构,父View仅负责边框、阴影效果,新增和父View同背景色的内层容器包裹所有内容,避免阴影透到文本层,适合内部存在多组文本、组件的场景,可维护性更高
// 布局调整 <View style={styles.reviewBox}> <View style={styles.innerContainer}> <Text style={{fontSize: 14, color: 'black'}}> Why does this text have shadows on it </Text> </View> </View> // 样式调整 reviewBox: { width: 300, height: 50, borderTopWidth: 0, borderBottomWidth:.5, borderRightWidth: .5, borderLeftWidth: .5, borderColor: 'white', borderBottomLeftRadius: 10, borderBottomRightRadius: 10, shadowColor: "#000000", shadowOpacity: 1, shadowRadius: 1, shadowOffset: { height: 1, width: 1 } }, innerContainer: { width: '100%', height: '100%', backgroundColor: 'white', // 与父View背景色保持一致 borderBottomLeftRadius: 10, borderBottomRightRadius: 10, overflow: 'hidden' }
内容的提问来源于stack exchange,提问作者Justin Priede
相关产品推荐
相关产品推荐

