簡體   English   中英

有什么方法可以與 blazor 頁面的主要布局進行通信

[英]Is there any way to communicate to main layout of blazor pages

這里我想將一些標題傳遞給 mainlayout.razor 頁面,以便我的組件或頁面可以更新 header 的標題。 blazor 中是否有任何可能的方法來做到這一點? 任何幫助將不勝感激。

@inherits LayoutComponentBase

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <div class="main">
        <div class="top-row px-4 bg-success">
            <button onclick="toggleNav()">
                <span class="oi oi-menu"></span>
            </button>
            <div class="text-center">
                hey there
            </div>
        </div>

        <div class="content px-4">
            @Body
        </div>
    </div>
    
</div>

@code
{

}

我的子組件是一個帶有@page 指令的路由器頁面,用於在頁面之間導航我希望該組件更新這個主布局有什么可能的方法嗎? 提前感謝您的幫助。

問候,

您應該使用 CascadingValue 組件包裝 MainLayout 組件的視圖部分,該組件的值是對 MainLayout 本身的引用,以便您可以引用 MainLayout 組件,例如,從 Counter 組件中,您可以從中為屬性分配值字符串在 MainLayout 組件中定義的標題。 此屬性還包含對 StateHasChanged 方法的調用以刷新顯示...

 @page "/counter"



// Gets a reference to the MainLayout component
    [CascadingParameter]
    public MainLayout Layout { get; set; }


    protected override void OnInitialized()
    {
        Layout.Title = "Greetings from Counter";

    }

MainLayout.razor

@inherits LayoutComponentBase

<CascadingValue Value="this">
    <div class="page">
        <div class="sidebar">
            <NavMenu />
        </div>

        <div class="main">
            <div class="top-row px-4">
                @Title
                <LoginDisplay />
                <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
            </div>

            <div class="content px-4">
                @Body
            </div>
        </div>
    </div>

</CascadingValue>

@code
{
    private string title;

    public string Title
    {
        get => title;
        set
        {
            title = value;
            InvokeAsync(() => StateHasChanged());
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM