温馨提示:本篇博客的详细代码已发布到 git : https://gitcode.com/nutpi/HarmonyosNext 可以下载运行哦!
由于本人疏忽本教程的第一节忘记上传运行效果图拉, 因此在本章节进行补充, 哈哈哈!
// 优化前
@State private props: AvatarProps
// 优化后
private props: AvatarProps = {
shape: AvatarShape.CIRCLE,
size: AvatarSize.MEDIUM,
randomBgColor: false
}
@State private loadError: boolean = false
@State private bgColorValue: string = ''
优化说明:
// 优化前
Stack() {
Circle().fill(this.getBackgroundColor())
this.renderContent()
}
// 优化后
Stack({ alignContent: Alignment.Center }) {
if (this.props.randomBgColor || this.props.bgColor) {
Circle()
.fill(this.props.bgColor ?? this.bgColorValue)
.width('100%')
.height('100%')
}
// 内容渲染
}
优化说明:
// 图片模式优化
Image(this.props.src)
.width('100%')
.height('100%')
.objectFit(ImageFit.Cover)
.onError(() => {
this.loadError = true
this.props.onError?.()
})
优化建议:
// 颜色常量定义
const AVATAR_COLORS = {
primary: '#1890ff',
success: '#52c41a',
warning: '#faad14',
danger: '#f5222d'
}
// 随机颜色池
const RANDOM_COLORS = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae']
管理建议:
@Component
export struct Avatar {
// 1. 属性定义
private props: AvatarProps
@State private states: AvatarStates
// 2. 生命周期
aboutToAppear() { }
// 3. 私有方法
private getSize(): number { }
private getRandomColor(): string { }
// 4. 渲染方法
private renderBackground() { }
private renderContent() { }
// 5. 主体构建
build() { }
}
组织建议:
// 类型定义优化
type AvatarSize = 'mini' | 'small' | 'medium' | 'large'
type AvatarShape = 'circle' | 'square'
interface AvatarStates {
loadError: boolean
bgColorValue: string
}
优化建议:
至此,Avatar组件的开发教程系列已经完结。希望这些内容能够帮助你更好地理解和使用Avatar组件,构建出更优秀的应用界面!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。