【问题标题】:Why is my blazor component with ElementReference and IJSRuntime.InvokeAsync inside for loop not working为什么我的带有 ElementReference 和 IJSRuntime.InvokeAsync 的 blazor 组件在 for 循环中不起作用
【发布时间】:2020-11-04 01:27:24
【问题描述】:

blazor(服务器)组件的标记中,我试图在循环中添加的每个元素上调用 javascript 函数。这有点难以解释......希望这段代码 sn-p 有所帮助:

@page "/"
@inject IJSRuntime JS
@for(var i = 0; i < 3; i++)
{
    ElementReference div;
    <div @ref="div">this should get replaced....</div>
    JS.InvokeVoidAsync("Test", div, i); @* where Test is defined as: function Test(el, i) { el.innerHTML = i; }*@
}

如果我以错误的方式进行此操作...正确的方式是什么?

关于更多上下文,这就是我实际上想要做的事情:

@page "/"
@inject IJSRuntime JS
@foreach(var data in jsonItems)
{
    ElementReference div;
    <div @ref="div"></div>
    JS.InvokeVoidAsync("JsonView.renderJSON", data, div); @* https://github.com/pgrabovets/json-view *@
}
@code
{
    private readonly IEnumerable<string> jsonItems = new List<string> {"{}", "{}"};
}

如果有帮助,我已经创建了这个 blazor fiddle...https://blazorfiddle.com/s/428ov3ku

【问题讨论】:

    标签: blazor blazor-server-side blazor-jsinterop


    【解决方案1】:

    在 ElementReference 对象被分配对元素的引用之前,您不能使用它。您的组件尚未创建和渲染,因此没有可用的 ElementReference 对象。您只能在渲染组件后使用 ElementReference 对象。

    你可以这样做:

    @inject IJSRuntime JSRuntime
    
    @foreach (var div in divs)
    {
      
        <div @ref="div.ElementReference"></div>
      
    }
    @code
    {
        private readonly IEnumerable<Div> divs = new List<Div> { new Div{JSON="{1}" },
                                                                 new Div{JSON="{2}"},
                                                                 new Div{JSON="{3}"}};
    
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
    
            if (firstRender)
            {
                @foreach (var div in divs)
                {
                await JSRuntime.InvokeVoidAsync(
                   "exampleJsFunctions.jsonRenderer", div.JSON, div.ElementReference);
                
                }
         
            }
        }
    
        public class Div
        {
            public ElementReference ElementReference { get; set; }
            public string JSON { get; set; } 
    
        }
    
     }
    

    将脚本放在 _Host.cshtml 文件的底部...

     <script>
            window.exampleJsFunctions = {
                jsonRenderer: function (json, element) {
                    element.innerText = json;
                }
            }
        </script>
    

    【讨论】:

    • 我想这解释了 为什么 它不起作用。关于如何让它工作的任何建议?
    • 不错,谢谢!我实际上用字典尝试了类似的东西,但是使用 ElementReference 作为键不起作用,我猜是因为它是一个结构......ElementReference tree; &lt;div @ref=tree&gt;&lt;/div&gt; dict[tree] = v.Value;
    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    相关资源
    最近更新 更多