Blazor组件中的CSS隔离可以通过使用带有伪类的选择器来实现,这些伪类是基于组件的GUID生成的。下面是一个示例:
.card { background-color: white; border: 1px solid black; }
@code { private ElementReference myCard;
private void AddCard() { var cardElement = new ElementRef(myCard); var card = new CardComponent(); var container = new DivContainer();
// Set the style attribute on the container element to match the CSS class defined in Step 1
container.Style.Set("background-color", "white");
container.Style.Set("border", "1px solid black");
// Add the card component to the container element
container.AppendChild(card);
// Add the container element to the DOM, using the ElementRef for the myCard element
cardElement.AppendChild(container);
} }
这将创建一个按钮,当单击它时,将在容器元素中添加一个卡组件,并将其添加到DOM的myCard元素中。
请注意,这只是一个示例。在实际应用中,您可能需要更好地组织您的代码,并使用更具描述性的类名和选择器。但是,这个示例演示了如何通过代码向组件添加样式。