【问题标题】:Is it Possible to Import an Exported JavaScript Module Class as Interop Class in Blazor?是否可以在 Blazor 中将导出的 JavaScript 模块类作为互操作类导入?
【发布时间】:2021-04-04 06:18:30
【问题描述】:

在最新的 Visual Studio 2019 中为我的 Blazor 服务器端解决方案创建 Razor 类库时,我看到以下文件:

ExampleJsInterop.cs

    public class ExampleJsInterop : IAsyncDisposable
    {
        private readonly Lazy<Task<IJSObjectReference>> moduleTask;

        public ExampleJsInterop(IJSRuntime jsRuntime)
        {
            moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
               "import", "./_content/MyNamespace/exampleJsInterop.js").AsTask());
        }

        public async ValueTask<string> Prompt(string message)
        {
            var module = await moduleTask.Value;
            return await module.InvokeAsync<string>("showPrompt", message);
        }

        public async ValueTask DisposeAsync()
        {
            if (moduleTask.IsValueCreated)
            {
                var module = await moduleTask.Value;
                await module.DisposeAsync();
            }
        }
    }

exampleJsInterop.js

// This is a JavaScript module that is loaded on demand. It can export any number of
// functions, and may import other JavaScript modules if required.

export function showPrompt(message) {
  return prompt(message, 'Type anything here');
}

这很有趣。但是,我想做的是use classes instead。我在搜索过的任何链接中都没有看到对此的任何引用,我发现的最接近的 StackOverflow 问题是this one

是否可以在 JavaScript/浏览器中导出类,然后通过互操作将它们导入 Blazor?如果有,怎么做?

【问题讨论】:

    标签: javascript c# blazor blazor-server-side


    【解决方案1】:

    我所做的是在 wwwroot 外部的文件夹中使用这样的 TypeScript 类(伪代码),并将 tsconfig 设置为在类库中编译为 wwwroot:

    class SizeHelpers {
        public GetBoundingClientRect(element: HTMLElement): DOMRect {
            return element.getBoundingClientRect();
        }
    }
    

    然后使用它来导出它(在同一个文件中):

    export function getSizeHelpers(): SizeHelpers {
        return new SizeHelpers();
    }
    

    然后在 C# 中,我在 Service 中按需导入此文件:

        var helpersInstance = await helpersModule.InvokeAsync<IJSObjectReference>("getSizeHelpers");
        Helpers = new Helpers(helpersInstance);
    

    然后在 C# 中我这样做是为了使用该函数:

     public class SizeHelpers
        {
            private readonly IJSObjectReference _instance;
    
            public SizeHelpers(IJSObjectReference instance)
            {
                _instance = instance;
            }
    
            public ValueTask<BoundingClientRectangle> GetBoundingClientRect(ElementReference element)
            {
                return _instance.InvokeAsync<BoundingClientRectangle>("GetBoundingClientRect", element);
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2021-10-29
      • 1970-01-01
      相关资源
      最近更新 更多