gpt4 book ai didi

Blazor JsInterop : Div not available when JS invoked

转载 作者:行者123 更新时间:2023-12-01 22:50:42 26 4
gpt4 key购买 nike

问题涉及客户端 Blazor 组件。该组件包含一个被组件变量隐藏的 div( bool 打开)。

我需要组件在组件代码文件中显示 div 后运行一些 Javascript(以便调整它在屏幕上的位置),下面的代码应该更好地解释这一点:

Component.razor

<div id="select-@Id" class="select-component" style="position: relative;">
<div class="option-selected" @onclick="@OnClick" style="border: 1px solid black;">
@if (opened)
{
<div class="options-wrapper" style="position: absolute; top: 30px; left: 0; border:1px solid red; background-color: white; z-index: 100;">
Sample Content
</div>
}
</div>
</div>

Component.razor.cs

using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace Accounting.Web.Components.Select
{
public partial class Select
{
[Parameter]
public int Id { get; set; } = default!;

[Parameter]
public RenderFragment ChildContent { get; set; } = default!;

[Inject]
public IJSRuntime JSRuntime { get; set; }

private IJSObjectReference jsModule;

public bool opened = false;


public void OnClick()
{
opened = !opened;

if (opened)
{
jsModule.InvokeVoidAsync("adjustPosition", "select-" + Id);
}
}

protected override async Task OnInitializedAsync()
{
jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/test.js");
}
}
}

测试.js

export function adjustPosition(node) {
console.log(node);
console.log($("#" + node + " .options-wrapper").length); // this always 0
}

问题是当我调用 JS 时,OnClick 事件中显示的 div (.options-wrapper) 尚不可用,因此 JS 脚本无法访问它。

我怀疑这可以通过在 JS 脚本中添加一个计时器来解决,但是我想知道是否有更简单的 hackier 解决方案可以解决我的上述问题?

最佳答案

您应该创建一个 ElementReference 对象并将其传递给 jsModule.InvokeVoidAsync。 ElementReference 对象将包含对 div 元素的引用

<div @ref="ReferenceToDiv" id="select-@Id" style="background-color: red; width:300px; height: 300px">

</div>

@code
{
ElementReference ReferenceToDiv;
// As you can see, you should call the "adjustPosition" method from the
// `OnAfterRenderAsync` method to ensure that the div element has been
// rendered. DO Not Re-render In Vain. That is, do not use
// await Task.Delay(1); to re-render your component

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (opened)
{
await jsModule.InvokeVoidAsync("adjustPosition", ReferenceToDiv);
}
}

public void OnClick()
{
opened = !opened;

}
}

测试.js

export function adjustPosition(element) {
// Should return 300px
console.log($(element.style.width);
}

关于Blazor JsInterop : Div not available when JS invoked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74424648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com