From dc1a76c835f6981cea86522e4a1a7839546b7ae3 Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Fri, 15 Nov 2024 03:44:21 -0800 Subject: [PATCH] fix(Checkbox): not trigger OnStateChanged callback when set TValue to bool (#4667) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: 修复布尔值时不触发 OnStateChanged 回调问题 * test: 增加单元测试 --- .../Components/Checkbox/Checkbox.razor.cs | 22 ++++++++++--------- test/UnitTest/Components/CheckboxListTest.cs | 21 ++++++++++++++++++ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/BootstrapBlazor/Components/Checkbox/Checkbox.razor.cs b/src/BootstrapBlazor/Components/Checkbox/Checkbox.razor.cs index 528c7c785..548e5f967 100644 --- a/src/BootstrapBlazor/Components/Checkbox/Checkbox.razor.cs +++ b/src/BootstrapBlazor/Components/Checkbox/Checkbox.razor.cs @@ -215,21 +215,23 @@ public partial class Checkbox : ValidateBase 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; } diff --git a/test/UnitTest/Components/CheckboxListTest.cs b/test/UnitTest/Components/CheckboxListTest.cs index 278ab9485..60f582fa2 100644 --- a/test/UnitTest/Components/CheckboxListTest.cs +++ b/test/UnitTest/Components/CheckboxListTest.cs @@ -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>(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() {