[英]How can I dispose (destroy) a component from a page in Blazor Server?
I would like to know how to properly dispose (destroy) a modal window component after user closes it.我想知道如何在用户关闭模态 window 组件后正确处置(销毁)它。 The way it is now, it is removed from the DOM, but the instance stays in the server (the time value assigned to the form-control remains the same when the window is reopened) and the Dispose() in the component is not called.
现在的方式,它从DOM中删除,但实例留在服务器中(重新打开window时分配给表单控件的时间值保持不变)并且组件中的Dispose()没有被调用.
@page "/"
<button class="btn btn-primary" @onclick="@(e => modalWindow.Show())">Open Dialog</button>
<ModalWindowToDispose @ref="modalWindow" ></ModalWindowToDispose>
@code {
ModalWindowToDispose modalWindow;
void OpenDialog()
{
modalWindow.Show();
}
}
// ModalWindowToDispose Component ( Show here in the same page only for simplicity)
@implements IDisposable
@if (ShowPopup)
{
<div class="modal" tabindex="-1" style="display:block;margin-top:100px" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<input class="form-control" type="text" value="@temp" placeholder="" />
<button class="btn btn-primary" @onclick="@(e => ShowPopup = false)">Close</button>
</div>
</div>
</div>
}
@code {
bool ShowPopup = false;
string temp = DateTime.Now.ToLongTimeString();
public void Show()
{
ShowPopup = true;
StateHasChanged();
}
void IDisposable.Dispose()
{
string tttt = "";
}
}
In your code, the <ModalWindowToDispose />
instance is always part of the DOM.在您的代码中,
<ModalWindowToDispose />
实例始终是 DOM 的一部分。 You add or remove only the part of <div class="modal"... ></div>
, because of your if
statement above.由于上面的
if
语句,您只添加或删除了<div class="modal"... ></div>
的一部分。
To resolve this problem, you could use a container approach like the library Blazored.Modal it does, where they split the "modal problem" into two classes.要解决此问题,您可以使用容器方法,例如它所做的库Blazored.Modal ,它们将“模态问题”分为两个类。 The modal is the container and the ModelInstance the component that should be disposed when the modal is closed.
modal是容器, ModelInstance是在 modal 关闭时应该释放的组件。 If the modal instance is closed, it is removed from the container and hence disposed, because it is not part of the DOM anymore.
如果模态实例关闭,它会从容器中移除并因此被丢弃,因为它不再是 DOM 的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.