Consider the following Blazor code:
<code><Foo @ref="foo">
<Bar @ref="bar"/>
</Foo>
<button @onclick="() => LoadBar("some data")">Click</button>
@code {
private Bar bar = null!;
private void LoadBar(string data)
{
bar.SetData(data) // bar is null
foo.SetVisible(true); // foo is not null, but exception already thrown
}
}
</code>
<code><Foo @ref="foo">
<Bar @ref="bar"/>
</Foo>
<button @onclick="() => LoadBar("some data")">Click</button>
@code {
private Bar bar = null!;
private void LoadBar(string data)
{
bar.SetData(data) // bar is null
foo.SetVisible(true); // foo is not null, but exception already thrown
}
}
</code>
<Foo @ref="foo">
<Bar @ref="bar"/>
</Foo>
<button @onclick="() => LoadBar("some data")">Click</button>
@code {
private Bar bar = null!;
private void LoadBar(string data)
{
bar.SetData(data) // bar is null
foo.SetVisible(true); // foo is not null, but exception already thrown
}
}
When I click the button, I want it to call LoadBar
and pass some data to the referenced Bar
instance, but the instance is always null
. I’m not sure why, although it may be to do with the way it’s rendered by Foo
; i.e. if isVisible
is false
in Foo
, then Bar
will not be rendered.
What sort of approaches does Blazor provide for this scenario?
3