问题
I want to dynamically change the style of a sap.m.CustomListItem
of my list when I click on a button.
I used addStyleClass
and it works only in the onInit
method but not in the press` function, the style has been added but the view doesn't change.
Controller
pressbutton: function(oEvent) {
var o = oEvent.getParameter("value");
MessageToast.show(o.toString());
var listitem = this.getView().byId("IDCustomerListItem");
if (listitem.hasStyleClass("myListItemClass")) {
this.getView().byId("IDCustomerListItem").removeStyleClass("myListItemClass");
this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClasso");
} else {
this.getView().byId("IDCustomerListItem").addStyleClass("myListItemClass");
}
}
CSS
.myListItemClass {
width: 50% !important;
float: left;
}
.myListItemClasso {
width: 100% !important;
}
回答1:
Here is a working example: https://embed.plnkr.co/LAv1qfsUjX0Anu7S/.
Why it didn't work
The reason why it worked only in onInit
but not in the press handler is because the style was being applied to the template control. You probably have something like this in your view:
<List xmlns="sap.m" items="{/myCollection}"> <CustomListItem id="IDCustomerListItem"> <!-- template control --> <!-- ... --> </CustomListItem> </List>
In
onInit
, the template control ("IDCustomerListItem"
) applies the custom style, and then the framework clones the template control for each collection item before rendering.In the press handler, however, applying the style to the template control doesn't have any effects any longer since the list items have been already cloned and rendered. It won't trigger cloning again.
The sample solution I provided above applies the style to the list. When the user triggers an action (via Switch for example), the render manager adds a custom data attribute to the corresponding HTML element by which the CSS can be applied accordingly.
.myApp .sapMList.myList[data-awesomestyle] .sapMLIB {
/* my custom style */
}
See Binding in Control with "class" Attribute
回答2:
If it works in the onInit but not inside your pressbutton
event handler, I assume the following:
1) The handler is not assigned to the press event of your Button
2) Your list has many items and you are not correctly getting the IDs of the items.
It's confusing in your question what are the controls assigned to the IDs and it would be easier to check the root cause of that issue having the source code of your view as well.
来源:https://stackoverflow.com/questions/56394007/ui5-change-the-style-of-list-items-after-clicking-on-a-button