When using a custom component in an app, preferentially use the @Builder function to replace the custom component. The @Builder function does not create a tree node in the backend FrameNode node tree, which helps shorten the page loading and rendering duration.
// code-linter.json5
{
"rules": {
"@performance/avoid-overusing-custom-component-check": "warn",
}
} // 1. Define a custom @Builder function component.
@Builder
function UserCardBuilder(name: string, age?: number, avatarImage?: ResourceStr) {
Row() {
Row() {
Image(avatarImage)
.size({ width: 50, height: 50 })
.borderRadius(25)
.margin(8)
Text(name)
.fontSize(30)
}
Text(`Age:${age?.toString()}`)
.fontSize(20)
}
.backgroundColor(DEFAULT_BACKGROUND_COLOR)
.justifyContent(FlexAlign.SpaceBetween)
.borderRadius(8)
.padding(8)
.height(66)
.width('80%')
}
@Component
export struct UserCardList {
@State users: User[] = getUsers();
aboutToAppear(): void {
let message = 'hello world';
}
build() {
List({ space: 8 }) {
ForEach(this.users, (item: User) => {
ListItem() {
// 2. Use the @Builder function.
UserCardBuilder(item.name, item.age, item.avatarImage)
}
}, (item: User) => item.id)
}
.alignListItem(ListItemAlign.Center)
}
} import { util } from '@kit.ArkTS';
interface User {
id: string;
name: string;
age?: number;
avatarImage?: ResourceStr;
// introduction: string;
// ...
}
// Construct data.
const DEFAULT_BACKGROUND_COLOR = Color.Pink;
const getUsers = () => {
const USERS: User[] = [{
id: '1',
name: 'Zhang San',
}, {
id: '2',
name: 'Li Si',
}, {
id: '3',
name: 'Wang Wu',
}];
return Array.from(Array(30), (item: User, i: number) => {
return {
id: util.generateRandomUUID(),
name: USERS[i%3].name,
avatarImage: $r('app.media.avatar'),
age: 18 + i
} as User;
});
}
// User card list component
@Component
export struct UserCardList {
@State users: User[] = getUsers();
build() {
List({ space: 8 }) {
ForEach(this.users, (item: User) => {
ListItem() {
UserCard({ name: item.name, age: item.age, avatarImage: item.avatarImage })
}
}, (item: User) => item.id)
}
.alignListItem(ListItemAlign.Center)
}
}
// Custom user card component
@Component
struct UserCard {
@Prop avatarImage: ResourceStr;
@Prop name: string;
@Prop age: number;
build() {
Row() {
Row() {
Image(this.avatarImage)
.size({ width: 50, height: 50 })
.borderRadius(25)
.margin(8)
Text(this.name)
.fontSize(30)
}
Text(`Age:${this.age.toString()}`)
.fontSize(20)
}
.backgroundColor(DEFAULT_BACKGROUND_COLOR)
.justifyContent(FlexAlign.SpaceBetween)
.borderRadius(8)
.padding(8)
.height(66)
.width('80%')
}
} plugin:@performance/recommended plugin:@performance/all
For details about how to configure Code Linter check rules, see Code Linter.