我有一个包含两个组件的 Blazor 页面。其中一个组件有一个按钮,单击该按钮会生成一个随机数。另一个组件有一个文本区域,应显示生成的随机数。
<h1>Parent Page</h1>
<ProvideNumberComponent />
<DisplayNumberComponent />
@code {
}
Run Code Online (Sandbox Code Playgroud)
<h3>Provides Number</h3>
<button class="btn btn-primary" @onclick="CalculateNumber">Provide Number</button>
@code {
private void CalculateNumber(MouseEventArgs e)
{
Random rnd = new Random();
Int32 nextNumber = rnd.Next();
}
}
Run Code Online (Sandbox Code Playgroud)
<h3>Displays number</h3>
<textarea cols="9" rows="1" readonly style="font-family:monospace;" />
@code {
}
Run Code Online (Sandbox Code Playgroud)
从计算同级组件获取数字以显示在显示同级组件中的最简洁方法是什么?
我的代码的一个问题是,随机对象是在每次单击按钮时实例化的,而不是在初始化时实例化一次。通过将 Random 对象放置在单例服务类中并将其注入计算组件是否可以最好地解决这个问题?
在我看来,最好的解决方案是创建一个实现状态模式和通知程序模式的服务。以下代码描述了两个兄弟姐妹之间如何通过中介进行通信
public class NotifierService
{
public NotifierService()
{
}
int rnd;
public int RandomNumber
{
get => rnd;
set
{
if (rnd != value)
{
rnd= value;
if (Notify != null)
{
Notify?.Invoke();
}
}
}
}
public event Func<Task> Notify;
}
Run Code Online (Sandbox Code Playgroud)
添加这个:services.AddScoped<NotifierService>();
@inject NotifierService Notifier
@implements IDisposable
<h3>Provides Number</h3>
<button class="btn btn-primary" @onclick="CalculateNumber">Provide
Number</button>
@code
{
private void CalculateNumber(MouseEventArgs e)
{
Random rnd = new Random();
Int32 nextNumber = rnd.Next();
Notifier.RandomNumber = nextNumber;
}
public async Task OnNotify()
{
await InvokeAsync(() =>
{
StateHasChanged();
});
}
protected override void OnInitialized()
{
Notifier.Notify += OnNotify;
}
public void Dispose()
{
Notifier.Notify -= OnNotify;
}
}
Run Code Online (Sandbox Code Playgroud)
@inject NotifierService Notifier
@implements IDisposable
<hr />
<h3>Displays number</h3>
<textarea cols="9" rows="1" readonly style="font-family:monospace;">
@Notifier.RandomNumber
</textarea>
@code {
public async Task OnNotify()
{
await InvokeAsync(() =>
{
StateHasChanged();
});
}
protected override void OnInitialized()
{
Notifier.Notify += OnNotify;
}
public void Dispose()
{
Notifier.Notify -= OnNotify;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以在多个组件中注入和使用该服务,以及添加该服务可以提供的更多功能。通过事件处理程序实现通信可能会出现问题,除非是在父级和子级之间......
希望这有效...
| 归档时间: |
|
| 查看次数: |
2819 次 |
| 最近记录: |