fix(Checkbox): not trigger OnStateChanged callback when set TValue to bool (#4667)

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

* test: 增加单元测试
This commit is contained in:
Argo Zhang 2024-11-15 03:44:21 -08:00 committed by GitHub
parent ccd3bdb0ec
commit dc1a76c835
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 33 additions and 10 deletions

View File

@ -215,21 +215,23 @@ public partial class Checkbox<TValue> : ValidateBase<TValue>
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;
}

View File

@ -94,6 +94,27 @@ public class CheckboxListTest : BootstrapBlazorTestBase
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()
{