If I have a Blazor component called DoAction
that consists of nothing more than this...
@code {
public void DoItNow(Action action) =>
action();
}
...and I use it in another component as follows...
<p>@((MarkupString)_msg)</p>
<br/><button @onclick="DoItNow">Do it now</button>
<DoAction @ref="_doAction" />
@code {
private string _msg;
private DoAction _doAction;
private void DoItNow() =>
_doAction.DoItNow(() => _msg += $"<br/>{DateTime.Now.ToLongTimeString()}: DoItNow");
}
...then it works fine. I can click the button and the display gets updated.
However, if I change this so that the DoAction
shows a button and only performs the action when the button is clicked, it doesn't work, see below.
Updated DoAction
component...
<button class="btn btn-primary" @onclick="ButtonClicked">Click me</button>
@code {
private bool _showButton = false;
private Action _action;
public void DoItAfterButtonClick(Action action) {
// Hold on to the action for use below
_action = action;
_showButton = true;
}
private void ButtonClicked() {
_action();
_showButton = false;
}
}
Updated parent component...
<p>@((MarkupString)_msg)</p>
<br/><button @onclick="DoItAfterButtonClick">Do it after button click</button>
<DoAction @ref="_doAction" />
@code {
private DoAction _doAction;
private void DoItAfterButtonClick() =>
_doAction.DoItAfterButtonClick(
() => _msg += $"<br/>{DateTime.Now.ToLongTimeString()}: DoItAfterButtonClick");
}
...then when I click the button in the parent, the button in the DoAction
component appears, but when I click that, nothing happens until something else updates the UI. At that point, I see the message that wasn't displayed when I clicked the DoAction
component's button.
I tried adding a call to StateHasChanged()
inside DoAction
, but it didn't make any dfference. The only way I can get it to work is if I call StateHasChanged()
in the parent component...
private void DoItAfterButtonClick() =>
_doAction.DoItAfterButtonClick(
() => {
_msg += $"<br/>{DateTime.Now.ToLongTimeString()}: DoItAfterButtonClick";
StateHasChanged();
});
Anyone any idea why the UI is not updated in the second case?
question from:
https://stackoverflow.com/questions/65875949/action-passed-to-a-blazor-not-component-doesnt-update-the-parent-until-somethin 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…