问题
I am using Blazorise, which provide multiple base components such as <Button>
, with multiple parameters.
I would like to create a simple component which would render a <Button>
with one or two parameters hard-coded (such as Color="Colors.Primary")
and then pass the rest of the parameters onto the <Button>
.
This is what I would like to be able to write:
<PrimaryButton Outline>Text</Button>
I would like to achieve this without having to manually set all parameters available from <Button>
in PrimaryButton.razor
. I have been looking for a way to do this for some time but can't find anything. Is It even possible?
I already tried inheriting from Button
and writing <Button @attributes="@Attributes" Color="Colors.Primary">
but the implicit parameters are discarded.
回答1:
I think you still have to pass them as parameters by adding them to your custom component. For instance you could do a button with Color
and Outline
set but pass on the Block
parameter.
/* PrimaryButton.razor */
<Button Color="Color.Primary" Outline="true" Block="@Block">@ChildContent</Button>
@code {
[Parameter] public bool Block { get; set;}
[Parameter] public RenderFragment ChildContent { get; set; }
}
You could then use that new component as
<PrimaryButton Block="true">Some Text</PrimaryButton>
回答2:
You can use "Attribute Splatting" for this
suppose your Base Component is defined
<h1>Base Component</h1>
<div>Param1 = @Param1</div>
<div>Param2 = @Param2</div>
@code
{
[Parameter] public string Param1 { get; set; }
[Parameter] public string Param2 { get; set; }
}
And you want to pre-populate Param1, so you create a new MyComponent
<BaseComponent Param1="predefined" @attributes=Attributes/>
@code
{
[Parameter(CaptureUnmatchedValues=true)]
public Dictionary<string,object> Attributes { get; set; }
}
Now, you can use MyComponent in place of BaseComponent, and if you do not supply a value for Param1, it will be predefined (literally that value in this case)
So this markup:
<BaseComponent Param1="base" Param2="component"/>
<MyComponent Param1="my" Param2="component"/>
<MyComponent Param2="component"/>
Produces this output:
Base Component
Param1 = base Param2 = component
Base Component
Param1 = my Param2 = component
Base Component
Param1 = predefined Param2 = component
See a live sample on BlazorRepl : https://blazorrepl.com/repl/QEvucNFB408fLIXd18
来源:https://stackoverflow.com/questions/64431539/component-which-apply-default-parameters-to-other-component