从Blazor中的页面组件调用MainLayout中的方法 [英] Call method in MainLayout from a page component in Blazor
问题描述
我有一个Blazor应用程序,该应用程序具有MainLayout
页面,该应用程序具有@Body
来加载实际的页面内容.
I have a Blazor app with a MainLayout
page, which has a @Body
to load the actual page content.
在我的情况下,Index.razor
已加载到MainLayout
页面中.
In my case Index.razor
is loaded inside the MainLayout
page.
是否有一种方法可以从位于父页面中的子页面(Index.razor)中调用方法; MainLayout.razor
?
Is there a way to call a method from the child page (Index.razor) that lives in the parent page; MainLayout.razor
?
示例:
MainLayout.razor
MainLayout.razor
<div class="content">
<ul class="menu">
<li>menu item 1</li>
</ul>
@Body
</div>
@code
{
public async Task Test()
{
await JsRuntime.InvokeAsync<object>("console.log", "test parent");
}
}
Index.razor
Index.razor
<h1>This is the index page</h1>
<button @onclick="(async () => await btn_clicked())">Call parent method</button>
@code
{
// Call method in MainLayout
public async Task btn_clicked()
{
await parent.Test();
}
}
推荐答案
您可以结合使用级联值和EventCallback
来执行此操作.
You can do this with the combination of cascading values and EventCallback
.
首先,为您的Test
创建一个事件回调.这样做,在您的MainLayout.razor中添加以下代码.
First, create an event call back for your Test
. To do so, add the following code in your MainLayout.razor.
EventCallback btn_clicked => EventCallback.Factory.Create(this, Test);
或者,要确保只创建一次该对象,可以使用以下命令:
Or, to make sure you only create this object once, you can use the following:
EventCallback _btn_clicked = EventCallback.Empty;
EventCallback btn_clicked {
get {
if (_btn_clicked.Equals(EventCallback.Empty))
_btn_clicked = EventCallback.Factory.Create(this, Test);
return _btn_clicked;
}
}
接下来,请确保将此事件回调串联到您的身体上.
Next, make sure you cascade this event callback down your body.
<CascadingValue Value=btn_clicked >
@Body
</CascadingValue>
现在,在您的Index.razor代码中,设置属性:
Now, in your Index.razor code, set the property:
[CascadingParameter]
public EventCallback btn_clicked { get; set; }
这篇关于从Blazor中的页面组件调用MainLayout中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!