该问题涉及客户端 Blazor 组件。该组件包含一个被组件变量隐藏的 div(bool 打开)。
我需要组件在组件代码文件中显示 div 之后运行一些 Javascript(以便调整它在屏幕上的位置),下面的代码应该更好地解释这一点:
组件.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>
组件.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");
}
}
}
test.js
export function adjustPosition(node) {
console.log(node);
console.log($("#" + node + " .options-wrapper").length); // this always 0
}
问题是,当我调用 JS 时,OnClick 事件中显示的 div (.options-wrapper) 尚不可用,因此 JS 脚本无法访问它。
我怀疑这个问题可以通过在 JS 脚本中添加一个计时器来解决,但是我想知道是否有一个更简单的解决方案可以解决我上面的问题?
你应该创建一个ElementReference
对象并将其传递给jsModule.InvokeVoidAsync.
The 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;
}
}
test.js
export function adjustPosition(element) {
// Should return 300px
console.log($(element.style.width);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)