主要是传入的参数要对,不然会出现奇奇怪怪的问题而且还不报错,以此记下一是提醒以后的自己,二是希望帮到有缘人(学艺不精还望海涵
相关资料:文档中心
先是错误代码
@Component
export default struct DetailsData {
@Builder countMonthsCard(item:number){
......
}
build() {
Column(){
......
RowCountScrollList({
countList: this.months ,
customBuilderParam: this.countMonthsCard
//这里 customBuilderParam: this.countMonthsCard 传入的参数错了
})
...
}
}
}
//自定义横向滑动组件
@Component
struct RowCountScrollList {
@Prop countList: number[] = [];
@Builder customBuilder() {}
@BuilderParam
customBuilderParam: (item: number) => void = this.customBuilder;
....
ForEach(this.countList, (item: number, index: number) => {
this.customBuilderParam(item);
});
....
......
}
这里 customBuilderParam: this.countMonthsCard 传入的参数错了,本来我写的是this.countMonthsCard(item:number)然后就报错了,后来传入的才是上面的但是显示数据只有数组的第一个元素然后我把countlist直接换成了一个数组输入进去又可以正常显示整个数组。这时候我应该就意识到是数据传输方面的问题了,但是我又搞了好久。最后呈现一下正确代码,展示一下如何正确传输有参数传入的@Builder方法。
@Component
export default struct DetailsData {
@State months:number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
@State days: number[]=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31];
//需要传入的@Builder方法
@Builder countMonthsCard(item:number){
....
}
@Builder countDaysCard(item:number){
.....
}
build() {
Column(){
//这里用我代码原有的两个@Builder方法传入
//月份
// 初始化一个 RowCountScrollList 实例
// 并且传递两个参数:
RowCountScrollList({
// 第一个参数是 countList,它被赋值为 this.months(即当前实例的一个属性)
countList: this.months,
// 第二个参数是 customBuilderParam,它被赋值为一个箭头函数
// 这个函数接收一个名为 item 的数字参数,并且调用当前实例的 countMonthsCard 方法,传入 item 作为参数
customBuilderParam: (item: number): void => this.countMonthsCard(item)
})
.margin({bottom:'20vp'})
//日期
RowCountScrollList({
countList:this.days,
customBuilderParam:(item:number): void => this.countDaysCard(item)
})
}
}
}
//自定义横向滑动组件
@Component
struct RowCountScrollList {
@Prop countList: number[] = [];
scroller: Scroller = new Scroller();
@Builder customBuilder() {}
@BuilderParam
customBuilderParam: (item: number) => void = this.customBuilder;
build() {
Row() {
Stack({ alignContent: Alignment.TopStart }) {
Scroll(this.scroller) {
Row({space: 20}) {
ForEach(this.countList, (item: number, index: number) => {
this.customBuilderParam(item);
});
}
}
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.scrollBarColor(Color.Gray)
.scrollBarWidth(5)
.onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset);
})
.onScrollEdge((side: Edge) => {
console.info('To the edge');
})
.onScrollEnd(() => {
console.info('Scroll Stop');
})
.onScrollStart(() => {
console.info('Scroll Start');
});
}
}
}
}