目录

FAQs About Dynamic Attribute Setting

This topic addresses common issues related to dynamic attribute setting.

Using AttributeModifier to Set Component Dynamic Attributes Causes JS Crash

Symptom

A JS crash occurs after AttributeModifier is used to set dynamic attributes for a component.

Solution

Go to the error log as prompted, view the error cause, and rectify the fault. For details, see the code example below.

Code Example

This example binds AttributeModifier to a Button to demonstrate a scenario where AttributeModifier throws an exception when setting an unsupported attribute. After running the sample code, a JS Crash error occurs. Refer to the animation below to jump to the specific error scenario. In this example, deleting the reuseId-related code allows it to run normally.

// xxx.ets
// Set the custom AttributeModifier for the Button component attributes.
class MyButtonModifier implements AttributeModifier<ButtonAttribute> {

  applyNormalAttribute(instance: ButtonAttribute): void {
    instance.reuseId('String') // Deleting this line will allow the application to run normally.
    instance.backgroundColor(Color.Red)
  }
}

@Entry
@Component
struct attributeDemo {
  @State modifier: MyButtonModifier = new MyButtonModifier();

  build() {
    Row() {
      Column() {
        Button('Button')
          .attributeModifier(this.modifier)
      }
      .width('100%')
    }
    .height('100%')
  }
}