如何用React Native制作左右边缘带C形切口的矩形容器
React Native 实现带C形切口的卡片组件
实现思路
通过绝对定位的圆形视图模拟C形切口:将圆形的一半置于卡片外侧,另一半覆盖在卡片边缘,配合与父容器一致的背景色,就能实现“挖空”的C形效果。
完整代码实现
import React from 'react'; import { View, StyleSheet } from 'react-native'; const NotchedCard = ({ children, style }) => { return ( <View style={[styles.cardContainer, style]}> {/* 左侧C形切口 */} <View style={styles.leftNotch} /> {/* 右侧C形切口 */} <View style={styles.rightNotch} /> {/* 卡片内容容器 */} <View style={styles.content}>{children}</View> </View> ); }; const styles = StyleSheet.create({ cardContainer: { position: 'relative', overflow: 'hidden', backgroundColor: '#ffffff', borderRadius: 8, // 阴影配置 elevation: 4, // Android shadowColor: '#000000', // iOS shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, }, leftNotch: { position: 'absolute', left: -20, top: '50%', transform: [{ translateY: -20 }], width: 40, height: 40, backgroundColor: '#f0f0f0', // 需与卡片父容器背景色一致 borderRadius: 20, }, rightNotch: { position: 'absolute', right: -20, top: '50%', transform: [{ translateY: -20 }], width: 40, height: 40, backgroundColor: '#f0f0f0', // 需与卡片父容器背景色一致 borderRadius: 20, }, content: { padding: 16, paddingHorizontal: 24, // 加大水平内边距,避免内容被切口遮挡 }, }); export default NotchedCard;
使用示例
import { View, Text } from 'react-native'; import NotchedCard from './NotchedCard'; export default function App() { return ( <View style={{ flex: 1, backgroundColor: '#f0f0f0', padding: 20, justifyContent: 'center' }}> <NotchedCard> <Text style={{ fontSize: 16, color: '#333333' }}>带C形切口的卡片</Text> <Text style={{ fontSize: 14, color: '#666666', marginTop: 8 }}>支持自定义内容</Text> </NotchedCard> </View> ); }
调整说明
- 修改切口大小:调整
leftNotch和rightNotch的width/height值(保持宽高相等),同时同步修改left/right和translateY的数值(为宽高的一半)。 - 适配不同背景:将两个切口的
backgroundColor改为卡片所在父容器的背景色,确保切口视觉效果自然。
内容的提问来源于stack exchange,提问作者Hitesh Patre
相关产品推荐
相关产品推荐

