Blazor: Cascading Values and Parameters

2020年5月11日 48点热度 0人点赞 0条评论
内容目录

Cascading Values and Parameters


<CascadingValue Value="@_grandValue" Name="GrandValue">
    <Parent />
</CascadingValue>

When data needs to flow between parent and child components, there are various methods to pass parameters. However, it becomes less convenient when the hierarchy exceeds two levels. This situation becomes even more complicated when multiple child components are involved.

Cascading values and parameters provide a convenient way for ancestor components to offer values to all of their descendant components, thus addressing the aforementioned issues. They also facilitate coordination among components.

The CascadingValue component is used to wrap the component hierarchy. For instance, to invoke the next level's component from the ancestor component:

Place <Parent /> inside the <CascadingValue> component to create the hierarchy.


<CascadingValue Value="@_grandValue" Name="GrandValue">
    <Parent />
</CascadingValue>

Additionally, the lower-level components need to use properties to receive the parameters passed from their ancestor component, and these properties should be adorned with the [CascadingParameter] attribute.

    [CascadingParameter(Name = &quot;GrandValue&quot;)]
    string GrandValue { get; set; }

The Name is not mandatory.

An example of its usage is as follows:

Create three .razor files: Grand.razor (ancestor component), Parent.razor (parent component), and Child.razor (child component).

The content of Child.razor is as follows:


<div>
    Grandchild Component:
    <p>Passed Value: @ChildValue</p>
</div>
@code {
    [CascadingParameter(Name = "ChildValue")]
    string ChildValue { get; set; }
}

The content of Parent.razor is as follows:


The parent component does not perform any actions:
    <Child />

The content of Grand.razor is as follows:

@page "/g"
Ancestor Component:
<p>Passed Value: <input @bind="_ChildValue" /></p>
Hint: After modifying the value, click elsewhere to update the grandchild component's value.
<!--Value: Grandchild property name, Name: The Name value of the grandchild property’s CascadingParameter attribute-->
<CascadingValue Value="@_ChildValue" Name="ChildValue">
    <Parent />
</CascadingValue>
@code {
    private string _ChildValue = "666";
}

If multiple values need to be passed, use multiple CascadingValue components as follows:

file

痴者工良

高级程序员劝退师

文章评论