什么是沉浸式页面
以小程序为例
默认情况下小程序页面自带导航栏,页面内容不会覆盖到导航栏上面
将页面属性navigationStyle设置为custom
,可以隐藏导航栏,从而实现页面侵入到状态栏的效果。
这就是沉浸式
页面
Taro的沉浸式页面
Taro支持编译成小程序和web页面,小程序沉浸式页面上面已提及,那web页面呢?
web页面是渲染在webview里面的,因此webview是否有导航栏,能否覆盖到状态栏上面,是宿主环境控制的,大部分情况下,浏览器都是自带导航栏,因此web页面其实是做不了沉浸式页面的。
因此,我们只需要做好小程序页面的沉浸式设计,并且保证web页面正常展示即可。
沉浸式页面的问题
小程序沉浸式页面只需要一行代码
definePageConfig({
navigationStyle: 'custom'
})
我们看看小程序和web页面展示效果
小程序页面
web页面
可以看到,web和小程序都没有导航栏,并且小程序页面还覆盖到了状态栏上面。
所以,需要解决的问题是实现自定义导航栏,并且预留出状态栏高度。
实现
- 我们可以实现固定布局的导航栏,如果是小程序的话,导航栏顶部还要预留状态栏高度的内边距。
- 由于导航栏是固定布局,页面顶部还需要预留一部分高度等于导航栏的空间,避免页面被导航栏覆盖。我实现的方式是在导航栏组件内预留一个正常布局的元素,高度等于导航栏,这样在在页面中引入导航栏即可,不用再额外改页面样式。
获取状态栏高度
通过Taro.getWindowInfo可以获取状态栏高度statusBarHeight
导航栏组件
export default function ImmersionNavigation(props: {
navigationHeight?: number
backgroundColor?: string
children: any
}) {
const statusBarHeight = isH5 ? 0 : Taro.getWindowInfo()?.statusBarHeight ?? 0
const navigationHeight = props.navigationHeight || 50
// 若状态栏文字颜色为白色,需要设置背景颜色
const backgroundColor = props.backgroundColor || 'white'
// 沉浸式导航栏高度=状态栏高度+导航栏高度
const height = statusBarHeight + navigationHeight
const children = props.children
const mainStyles: CSSProperties = {
height: height + 'px',
backgroundColor,
paddingTop: statusBarHeight + 'px',
boxSizing: 'border-box',
position: 'fixed',
top: '0px',
left: '0px',
right: '0px',
display: 'flex',
alignItems: 'center'
}
return (
<>
{/* 固定布局吸顶,嵌入自定义的子元素作为标题 */}
<View style={mainStyles}>{children}</View>
{/* 静态布局,放在文档中撑起沉浸式页面顶部高度 */}
<View style={{ height: height + 'px' }}></View>
</>
)
}
页面组件
import { View } from '@fower/taro'
import ImmersionNavigation from '@/components/ImmersionNavigation'
definePageConfig({
navigationBarTitleText: '首页',
navigationStyle: 'custom', // 自定义导航栏
navigationBarTextStyle: 'black' // 导航栏文字颜色为黑色
})
export default function Index() {
return (
<View>
<ImmersionNavigation>
<View style={{ marginLeft: 'auto', marginRight: 'auto' }}>首页</View>
</ImmersionNavigation>
</View>
)
}
看看效果
小程序页面
web页面
End
原文链接:https://juejin.cn/post/7311904486965067817 作者:nick_h