Blazor:如何在 JSInterOP 调用后调用 StateHasChanged(在通过 JS resize 事件调整大小后尝试将浏览器分辨率获取到 Blazor 应用程序)?

问题描述 投票:0回答:1

在过去的几天里,我试图在我的 blazor 应用程序中读出浏览器分辨率。我正在尝试这样做:[JSInvokable] Blazor Methode 由 JS 脚本调用。

1. 我的问题是:宽度和高度仅在我重新加载(手动刷新)页面后显示在我的 blazorpage 中。我无法调用 this.StateHasChanged() 因为我的方法是静态的。

如何调用 StateHasChanged 或者我需要做什么才能显示新数据?我对 ASP.net 等还很陌生,所以如果可能的话请包含一个代码示例;)

这是我的 Code blazor(服务器端)代码:

@page "/"
@inject IJSRuntime jsRuntime
<h1>Window Dimensions</h1>

<p>Window Width: @Width</p>
<p>Window Height: @Height</p>
<p>@DebugString</p>

@code {
    public static int Width;
    public static int Height;
    public static string DebugString;

    [JSInvokable]
    public static async Task GetBrowserDimensions(int width, int height)
    {
        Width = width;
        Height = height;
        if (Width < 600)
        {
            DebugString = "small_UI";
        }
        if (Width >= 600)
        {
            DebugString = "big_UI";
        }
    }
}

这是我的 .js 代码:

//------JS Code for the resize stuff incl. timer so that resize doesnt fire every pixel move
var resizeId;
window.addEventListener('resize', function () {
    clearTimeout(resizeId);
    resizeId = setTimeout(doneResizing, 500);
});

function doneResizing() {
    var width= window.innerWidth;
    var height= window.innerHeight;
    alert('Width: ' +width + '  Height: ' +height);
    DotNet.invokeMethodAsync('Blazor_PageResolutionJS', 'GetBrowserDimensions', width, height);
}
//^^^^^^JS Code for the resize stuff incl. timer so that resize doesnt fire every pixel move

2. 这是获取浏览器分辨率以便做出用户界面设计选择的好技术吗?

感谢您的阅读

c# blazor window-resize blazor-jsinterop
1个回答
6
投票

您可以通过安装 NuGet 包来绕过此需求 https://www.nuget.org/packages/BlazorPro.BlazorSize/

如果您仍然对自己编写代码感兴趣,可以在 https://github.com/EdCharbeneau/BlazorSize/tree/master/BlazorSize

找到 BlazorSize 的源代码

从 JavaScript 调用 StateHasChanged 的解决方案涉及使用 .NET 中的 [JsInvokable] 方法。但是,如果您查看 BlazorSize 的源代码,您会发现在使用完事件侦听器后,需要做很多额外的工作才能从 DOM 中正确删除事件侦听器。

© www.soinside.com 2019 - 2024. All rights reserved.