React Native实现iOS/Android内嵌凹陷盒子及滚动卡片效果求助
实现React Native内凹嵌入容器效果
你要的是嵌入屏幕的内凹容器效果,React Native原生的boxShadow是向外的阴影,没法直接实现内阴影,得用模拟方案,下面给你两种可行的实现方式:
方案一:用线性渐变模拟内阴影(推荐,效果更贴合设计)
需要先安装react-native-linear-gradient依赖:
npm install react-native-linear-gradient # 或者用yarn yarn add react-native-linear-gradient
1. 封装内阴影容器组件
import React from 'react'; import { View } from 'react-native'; import LinearGradient from 'react-native-linear-gradient'; const InnerShadowContainer = ({ children, style }) => { return ( <View style={[style, { position: 'relative', overflow: 'hidden' }]}> {/* 顶部内阴影 */} <LinearGradient colors={['rgba(0, 0, 0, 0.25)', 'rgba(0, 0, 0, 0)']} style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 10, }} /> {/* 底部内阴影 */} <LinearGradient colors={['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0.25)']} style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 10, }} /> {/* 左侧内阴影 */} <LinearGradient colors={['rgba(0, 0, 0, 0.25)', 'rgba(0, 0, 0, 0)']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ position: 'absolute', top: 0, left: 0, bottom: 0, width: 10, }} /> {/* 右侧内阴影 */} <LinearGradient colors={['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0.25)']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: 10, }} /> {/* 内容容器,覆盖阴影中间区域 */} <View style={{ flex: 1, backgroundColor: '#ffffff', // 替换成你的屏幕背景色 borderRadius: style.borderRadius || 16, }}> {children} </View> </View> ); }; export default InnerShadowContainer;
2. 修改你的首页代码
把原来包含ScrollView的SafeAreaView替换成这个组件:
return isLoading ? ( <LoadingComponent /> ) : ( <> <SafeAreaView style={Layout.fill}> <View style={[Layout.alignItemsStart, Gutters.largeTMargin, Gutters.largeLMargin]}> <Text style={common.headingTextStyle}>{welcomeUser}</Text> <Text style={[Gutters.regularTMargin, common.subHeadingTextStyle]}>Available</Text> </View> {/* 替换原来的SafeAreaView为内阴影容器 */} <InnerShadowContainer style={[ Layout.fill, Gutters.regularHMargin, Gutters.regularVMargin, { borderRadius: 16 }, // 匹配设计图的圆角 ]} > <ScrollView style={[ Layout.fullSize, Gutters.regularLPadding, Gutters.regularRPadding, Gutters.largeBMargin, ]} > {_.map(jobs, (job) => ( <Job jobData={job} key={_.get(job, 'id')} /> ))} </ScrollView> </InnerShadowContainer> </SafeAreaView> </> );
方案二:纯原生View模拟(无需第三方库)
如果不想引入依赖,可以用双层View叠加的方式实现简易内凹效果:
const SimpleInnerShadowContainer = ({ children, style }) => { return ( <View style={[style, { backgroundColor: 'rgba(0, 0, 0, 0.1)', borderRadius: 16, padding: 3, // 阴影厚度 }]}> <View style={{ flex: 1, backgroundColor: '#ffffff', // 屏幕背景色 borderRadius: 13, // 外层padding是3,所以圆角比外层小3 }}> {children} </View> </View> ); };
使用方式和方案一一致,这种方式效果偏淡,适合对阴影要求不高的场景。
注意事项
- 确保内容容器的
backgroundColor和屏幕背景色完全一致,否则内凹效果会显得不协调 - 可以调整渐变的透明度、高度/宽度,或者阴影颜色,来匹配设计图的效果
内容的提问来源于stack exchange,提问作者Jennifer De Goede
相关产品推荐
相关产品推荐

