i'm making a carousel of images and i've the error : The left-hand side of an assignment expression may not be an optional property access

i'm making a carousel of images and i've the error : The left-hand side of an assignment expression may not be an optional property access

我正在 Angular 中制作一个图像轮播,它接收一个模型来迭代图像,但是当我尝试占据第一个位置时它抛出了一个错误。

赋值表达式的左侧不能是可选的 属性 access.ts(2779)

The error is here

export class CarouselComponent implements OnInit {
@Input() height = 500;
@Input() isFullScreen = false;
@Input() items: ICarouselItem[] = [];

public finalHeight: string | number = 0;
public currentPosition = 0;

constructor() {
 this.finalHeight = this.isFullScreen ? '100vh' : `${this.height}px`;
}

ngOnInit(): void {
this.items.map((i, index) =>{
  i.id = index;
  i.marginLeft = 0;
});
}

setCurrentPosition(position: number){
debugger
this.currentPosition = position;
this.items.find(i => i.id === 0)?.marginLeft = -100 * position;

}

setNext(){
debugger
let finalPercentage = 0;
let nextPosition = this.currentPosition + 1;
if(nextPosition <= this.items.length - 1){
  finalPercentage = -100 * nextPosition;
}else{
  nextPosition = 0;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = nextPosition;
}

setBack(){
let finalPercentage = 0;
let backPosition = this.currentPosition -1;
if(backPosition >= 0){
  finalPercentage = -100 * backPosition;
}else{
  backPosition = this.items.length - 1;
  finalPercentage = -100 * backPosition;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = backPosition;
}
}

我认为显示此错误是因为您正在使用 find 函数并直接为该对象赋值 喜欢

this.items.find(i => i.id === 0)?.marginLeft = -100 * position

假设您没有找到该对象,那么它将 return null 那么如何在 marginLeft 中分配值。我想首先你必须检查你是否使用 find 函数得到任何值,然后执行 set value to marginLeft.

我认为这可能是个问题,您使用此代码 3 次。这些更改后,如果您无法修复,我们将在此处发表评论以进一步检查。

你可以试试:

let item = this.items.find(i => i.id === 0);
if(item){
 item.marginLeft = -100 * position;
 // you can modify object here and do other things 

}