Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

Is there a way to add a class name to a blazor component without overriding the existing class name?

Suppose I have a component, MyComponent, declared as follow:

<div class="container">
  "some nested content"
</div>

now I want to consume the component, and give it a class name:

<MyComponent class="new-class" />

If I do this, the "container" class name will be overridden by "new-class":

<div class="new-class">
  ....
<div>

Is there a way to keep both class names and have, at the end:

<div class="container new-class">
  ....
<div>
question from:https://stackoverflow.com/questions/65944445/is-there-a-way-to-add-a-class-name-to-a-blazor-component-without-overriding-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should to learn about "Component Parameters": [Parameter]. On your component, declare a parameter:

<div class="container @CssClass">
  "some nested content"
</div>

@code
{
   [Parameter] public string CssClass {get; set;} = "";
}

Now, when you use your component, if you want, you can set a value to the parameter:

<MyComponent CssClass="new-class" />

Quoting docs:

Components can have component parameters, which are defined using public simple or complex properties on the component class with the [Parameter] attribute. Use attributes to specify arguments for a component in markup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...