Javascript 在 Razor 组件中

Javascript in Razor component

我正在尝试在剃须刀组件中加载 javascript 函数,但出现错误。

@inject IJSRuntime JsRuntime

@if (listProducts != null)
{
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Home place</th>
                <th>Expiration</th>
                <th>Phone number</th>
                <th>Tea</th>
                <th>Local</th>
                <th>App</th>
                <th>Company /Lease</th>
                <th>Road time</th>
                <th>Notes</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach(var product in this.listProducts)
            {
                <ProductItemComponent 
                    Product="product"
                    OnProductDeleted="OnProductDeleted"></ProductItemComponent>
            }
        </tbody>
    </table>    
}

@code {

    protected override async Task OnInitializedAsync()
    {
        await LoadProducts();
        await JsRuntime.InvokeVoidAsync("exampleJsFunctions.DisableCopy");
    }
}

一开始我像这样注入 IJSRuntime @inject IJSRuntime JsRuntime 并且在 OnInitializedAsync() 中我调用我的函数 _Layout.cshtml 看起来像这样

<script>
        window.exampleJsFunctions =
            {
                DisableCopy: function (data) {
                    if (document.layers) {
                        document.captureEvents(Event.MOUSEDOWN);
                        document.onmousedown = clickNS4;
                    }
                    else if (document.all && !document.getElementById) {
                        document.onmousedown = clickIE4;
                    }
                  }}
    
    </script>

这是控制台的错误

有什么问题吗?

这里有一个在blazor中调用js的demo:

wwwroot/js/test.js(将js代码放到wwwroot的js文件中):

window.exampleJsFunctions =
            {
                DisableCopy: function (data) {
                    if (document.layers) {
                        document.captureEvents(Event.MOUSEDOWN);
                        document.onmousedown = clickNS4;
                    }
                    else if (document.all && !document.getElementById) {
                        document.onmousedown = clickIE4;
                    }
                  }}

Pages/_Host.cshtml(在_Host.cshtml中添加test.js的引用):

...
<html lang="en">
<head>
    ...
</head>
<body>
  ...
    <script src="~/js/test.js"></script>
</body>
</html>

不要在 OnInitializedAsync() 中调用 js。组件正在静态 rendered.SO JavaScript 无法在此 time.So 发出互操作调用,您可以在 OnAfterRender.

剃须刀组件:

@inject IJSRuntime JsRuntime
@code {
   protected override void OnAfterRender(bool firstRender)
{
    JsRuntime.InvokeVoidAsync("exampleJsFunctions.DisableCopy");
}
}