【问题标题】:Background Color keep updating on click or scroll背景颜色在点击或滚动时不断更新
【发布时间】:2019-11-05 08:31:12
【问题描述】:

我有一个生成背景颜色的功能(工作正常),但问题是当我点击屏幕上的任意位置时,或者有时甚至滚动页面时会一次又一次地更改背景颜色。

HTML:

<ion-button shape="round" color="clear" [ngStyle]="{'background':getRandomColor(), 'border-radius': '20px'}" *ngFor="let c of categories;">{{c.title}}</ion-button>

.ts

 getRandomColor(){
    let color = "#";
    for (let i = 0; i < 3; i++)
    {
        let part = Math.round(Math.random() * 255).toString(16);
        color += (part.length > 1) ? part : "0" + part;
    }
   return color;    
  }

现在每次用户单击按钮或屏幕上的任何位置时,颜色都会自动更改,这很烦人。 我的控制台中也出现此错误。

ProfilePage.html:44 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'background: #de5d88'. Current value: 'background: #2ce111'.
    at viewDebugError (core.js:20440)
    at expressionChangedAfterItHasBeenCheckedError (core.js:20428)
    at checkBindingNoChanges (core.js:20530)
    at checkNoChangesNodeInline (core.js:23401)
    at checkNoChangesNode (core.js:23390)
    at debugCheckNoChangesNode (core.js:23994)
    at debugCheckDirectivesFn (core.js:23922)
    at Object.eval [as updateDirectives] (ProfilePage.html:44)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
    at checkNoChangesView (core.js:23289

编辑: 类别来自服务器以供选择。

this.categories= [
 "Horror1"
 "Horror2"
 "Horror3"
]

【问题讨论】:

  • 这是因为更改检测是在用户交互时触发的,所以每次都会调用getRandomColor。您应该设置一次背景颜色。请分享更多您的代码库(包括您如何定义categories 的部分)以便能够提供解决方案。
  • Categories Sample 添加到问题中。

标签: javascript android angular ionic-framework


【解决方案1】:

这是因为更改检测是在用户交互时触发的,所以每次都会调用getRandomColor。您应该设置一次背景颜色。

// Some place where categories are defined
this.categories = this.categories.map(category=> ({...category, bgColor: this.getRandomColor()}));
<ion-button shape="round" color="clear" [ngStyle]="{'background': category.bgColor, 'border-radius': '20px'}" *ngFor="let c of categories;">{{c.title}}</ion-button>

【讨论】:

  • 我有这个想法来重新初始化包含颜色对象的类别数组,但我正在寻找更好的解决方案。虽然我这样做了,但它奏效了。但如果您有更好的解决方案,请讨论。因为有时有 1000 多个类别和子类别,我认为这样做不好。
【解决方案2】:

请创建一个带有数据和颜色的模型,然后在适配器中设置,在您滚动它的情况下,会调用 onBindViewHolder 并再次生成新颜色。所以请在类中使用 randomcolor() 方法,而不是在适配器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2021-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多