Skip to content

Commit

Permalink
fix(Checkbox): not trigger OnStateChanged callback when set TValue to…
Browse files Browse the repository at this point in the history
… bool (#4667)

* refactor: 修复布尔值时不触发 OnStateChanged 回调问题

* test: 增加单元测试
  • Loading branch information
ArgoZhang authored Nov 15, 2024
1 parent ccd3bdb commit dc1a76c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/BootstrapBlazor/Components/Checkbox/Checkbox.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,21 +215,23 @@ private async Task<bool> InternalStateChanged(CheckboxState state)
if (IsBoolean)
{
CurrentValue = (TValue)(object)(state == CheckboxState.Checked);
}

if (State != state)
{
State = state;
if (StateChanged.HasDelegate)
if (ValueChanged.HasDelegate)
{
await StateChanged.InvokeAsync(State);
ret = false;
}
}

if (OnStateChanged != null)
{
await OnStateChanged(State, Value);
}
State = state;
if (StateChanged.HasDelegate)
{
await StateChanged.InvokeAsync(State);
ret = false;
}

if (OnStateChanged != null)
{
await OnStateChanged(State, Value);
}
return ret;
}
Expand Down
21 changes: 21 additions & 0 deletions test/UnitTest/Components/CheckboxListTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,27 @@ public async Task Checkbox_OnTriggerClickAsync()
Assert.Equal(CheckboxState.Checked, cut.Instance.State);
}

[Fact]
public async Task Bool_TriggerStateChanged_Ok()
{
bool value = false;
// 测试 bool 值改变值时触发 StateChanged 回调方法
var cut = Context.RenderComponent<Checkbox<bool>>(pb =>
{
pb.Add(a => a.Value, false);
pb.Add(a => a.OnStateChanged, (state, v) =>
{
value = v;
return Task.CompletedTask;
});
});

// JavaScript 调用 OnTriggerClickAsync 方法
await cut.InvokeAsync(() => cut.Instance.OnTriggerClickAsync());
Assert.Equal(CheckboxState.Checked, cut.Instance.State);
Assert.True(value);
}

[Fact]
public void Checkbox_Dispose()
{
Expand Down

0 comments on commit dc1a76c

Please sign in to comment.