组件关联

可以关联父子组件

父组件

如果是 .razor 组件,需要手动使用 CascadingValue 传入当前组件

List.razor
@inherits BlazorComponentBase

<CascadingValue Value="this">
    <ul @attributes="AdditionalAttributes">@ChildContent</ul>
</CascadingValue>

如果是组件类,仅需要定义 ParentComponent 特性即可

[ParentComponent]
public class List : BlazorComponentBase
{
}

子组件

定义 ChildComponent 特性关联父组件

ListItem.razor
@inherits BlazorComponentBase
@attribute [ChildComponent(typeof(List))]

<!--.NET 7-->
@attribute [ChildComponent<List>]

<li @attributes="@AdditionalAttributes">
    @ChildContent
</li>

@code{
    [CascadingParameter]public List CascadedList { get; set; }
    
    protected override void BuildCssClass(ICssClassBuilder builder)
    {
        if(CascadedList.Active)
        {
            //..
        }
    }
}

组件 ListItem 必须放在 List 组件中,否则将抛出异常

Optional

true 时将忽略强制关联,不抛出异常

Last updated