代码之家  ›  专栏  ›  技术社区  ›  Jeahel

将默认参数应用于其他组件的组件

  •  0
  • Jeahel  · 技术社区  · 5 年前

    <Button> 我想创建一个简单的组件,将呈现一个 <按钮> Color="Colors.Primary") 然后将其余参数传递到 < .

    这就是我想写的:

    <PrimaryButton Outline>Text</Button>
    

    < 在里面 PrimaryButton.razor . 我一直在寻找一种方法来做这一点有一段时间,但找不到任何东西。有可能吗?

    我已经试过继承 Button <Button @attributes="@Attributes" Color="Colors.Primary"> 但是隐式参数被丢弃了。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Douglas Riddle    5 年前

    我认为您仍然需要通过将它们添加到自定义组件来将它们作为参数传递。例如,你可以用 Color Outline 设置但传递 Block 参数。

    /* 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; }
    }
    

    然后你就可以用这个新组件

    <PrimaryButton Block="true">Some Text</PrimaryButton>
    
        2
  •  1
  •   Mister Magoo    5 年前

    您可以使用“属性散点”来进行此操作

    假设您的基本组件已定义

    <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; }
    }
    

    你想预先填充Param1,所以你要创建一个新的MyComponent

    <BaseComponent Param1="predefined" @attributes=Attributes/>
    @code
    {
      [Parameter(CaptureUnmatchedValues=true)] 
      public Dictionary<string,object> Attributes { get; set; }       
    }
    

    现在,您可以使用MyComponent代替BaseComponent,如果您没有为Param1提供值,它将是预定义的(在本例中按字面意思是该值)

    所以这个标记:

    <BaseComponent Param1="base" Param2="component"/>
    
    <MyComponent Param1="my" Param2="component"/>
    
    <MyComponent Param2="component"/>
    

    生成此输出:

    基本组件

    Param1=基础 Param2=组件

    Param1=我的 Param2=组件

    Param2=组件

    查看BlazorRepl上的实时示例: https://blazorrepl.com/repl/QEvucNFB408fLIXd18