往期鸿蒙5.0全套实战文章必看:(文中附带全栈鸿蒙5.0学习资料)
WebViewComponent实现自定义Web页面
导入依赖
import {WebViewComponent} from '@peakmain/library';
参数
参数 | 参数类型 | 是否必填 | 说明 |
---|
url | string | 否 | 跳转的url,默认是空字符串 "" |
controller | webview.WebviewController | 是 | web控制器,可以控制Web组件各种行为 |
title | string | 是 | 标题,根据网页document标题展示对应标题 |
showTitle | boolean | 否 | 显示标题 |
currentProgressNumber | number | 是 | 当前进度 |
onErrorReceive | (e: OnErrorReceiveEvent) => void | 否 | 错误回调,默认为空 |
示例代码
import { router } from '@kit.ArkUI'
import { webview } from '@kit.ArkWeb'
import { NavBar, WebViewComponent } from '../../components'
import { AVOID_AREA_HEIGHT, STATUS_BAR_HEIGHT } from '../../common'
import { WebViewBean } from '../../models'
@Entry({ routeName: "PkWebViewPage" })
@Component
struct PkWebViewPage {
@StorageProp(STATUS_BAR_HEIGHT) statusBarHeight: number = 0
@StorageProp(AVOID_AREA_HEIGHT) bottomSafeAreaHeight: number = 0;
@State url: string = ""
@State
controller: webview.WebviewController = new webview.WebviewController()
@State
title: string = ""
@State
showTitle: boolean = true
@State
currentProgressNumber: number = 0
onErrorReceive?: (e: OnErrorReceiveEvent) => void
progressColor: ResourceColor = $r("app.color.color_A78461")
aboutToAppear(): void {
let bean = router.getParams() as WebViewBean
this.url = bean.url
this.showTitle = bean.showTitle
}
build() {
Column() {
if (this.showTitle) {
NavBar({
title: this.title,
titleColor: Color.Black,
leftClick: () => {
if (this.controller.accessBackward()) {
this.controller.backward()
} else {
router.back()
}
}
})
}
if (this.currentProgressNumber < 100) {
Progress({
value: this.currentProgressNumber
}).color(this.progressColor)
}
WebViewComponent({
url: this.url,
controller: this.controller,
currentProgressNumber: this.currentProgressNumber,
title: this.title,
showTitle: this.showTitle,
onErrorReceive: this.onErrorReceive
})
}
.padding({ top: this.statusBarHeight })
.margin({
bottom: this.bottomSafeAreaHeight
})
.size({ width: '100%', height: '100%' })
}
}
}
