[英]Passing Cascading Parameters to Blazor component that rendered from JavaScript
我想將CascadingParameter
傳遞給 Counter 頁面組件,但我不想使用路由器。 Instead of that, I want to use JavaScript because I want the component to be rendered inside the window of Winbox.js (open-source HTML5 window manager).
問題是級聯參數被初始化為null
,我認為這是由於RenderTree
的差異而發生的。
這是我的代碼:
在Program.cs
中為 JavaScript 注冊Counter.razor
組件:
builder.RootComponents.RegisterForJavaScript<Counter>(identifier: "counter");
對於MainLayout.razor
<!-- omitted for brief -->
<CascadingValue Value="_TestCascadingParameter">
<article class="content px-4">
@Body
</article>
</CascadingValue>
<!-- omitted for brief -->
@code{
private TestCascadingParameter _TestCascadingParameter = new() { GlobalCounter = 5 };
public class TestCascadingParameter
{
public int GlobalCounter { get; set; }
}
對於計數器頁面:
@page "/counter"
@using static BlazorApp1.Shared.MainLayout
<PageTitle >Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
[CascadingParameter]
public TestCascadingParameter TestCascadingParameter { get; set; }
private int currentCount = 0;
protected override void OnParametersSet()
{
currentCount = TestCascadingParameter.GlobalCounter;
}
private void IncrementCount()
{
currentCount++;
}
}
對於 Winbox 頁面:
@page "/WinBox"
@layout MainLayout
@inject IJSRuntime _Js
<PageTitle>Win box</PageTitle>
<button @onclick="@OpenWinAsync">Open window</button>
@code{
async Task OpenWinAsync()
{
await _Js.InvokeVoidAsync("MyWinBox.OpenTestWindow");
}
}
對於MyWinBox.js
:
window.MyWinBox = {
OpenTestWindow: async () => {
let containerElement = new WinBox("WinBox.js");
await Blazor.rootComponents.add(containerElement.body, 'counter', {});
}
};
當我使用路由器導航到計數器頁面時,一切正常並且 currentCount 從 5 開始,但是當我使用 JavaScript 渲染它時,它會在 TestCascadingParameter 上引發 NullReferenceException。
如何在不通過 JavaScript 傳遞級聯參數值的情況下解決此問題,因為有時級聯參數在調用方組件中具有null
值,如上例所示(例如:如果調用方組件是 MudDialog),或者有時有多個級聯參數。
RegisterForJavaScript 是新的,沒有詳細記錄的功能,我不知道是否可以傳遞這樣的級聯參數。 但我認為您可以使用 State 容器(或 Fluxor 之類的東西)來實現您的目標:
public class StateContainer
{
private int? globalCounter;
public int Property
{
get => globalCounter;
set
{
globalCounter = value;
NotifyStateChanged();
}
}
public event Action? OnChange;
private void NotifyStateChanged() => OnChange?.Invoke();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.