【问题标题】:Clear input with is binded to event using button清除输入与使用按钮绑定到事件
【发布时间】:2021-10-02 10:39:57
【问题描述】:

您好,我正在为简单项目使用 Blazor 框架,简而言之,我有一个输入和一个按钮:

<input type="text" id="modal_table_autosearch" placeholder=" " @oninput="@(async args => await this.Filter(args))" />
<label for="modal_table_autosearch">Search by name</label>
                
<button type="button" @onclick="@(async _ => await this.Filter(null))">
    <i class="far fa-trash-alt"></i>
</button>

正如您所见,当我开始输入时,我的输入事件被触发,当我按下下面的这个按钮时,我希望它重置结果并清除输入。 重置的东西很好,但我不知道如何清除输入。我可以将业务转移到财产并在那里做事,但我觉得这会增长,财产还不够。

这是我的事件代码:

     protected async ValueTask Filter(ChangeEventArgs args)
    {
        if (args == null || string.IsNullOrEmpty(args.Value?.ToString()))
        {
            this.SetFilteringCollections();
            return;
        }

        var searchValue = args.Value?.ToString();
        // thing I do with string but I think there will be more complicated object pass as argument that's why event

        await this.InvokeAsync(this.StateHasChanged);
    }

【问题讨论】:

    标签: c# html blazor


    【解决方案1】:

    这是您的代码的简化版本。将输入绑定到属性或模型中的属性。

    您还使将任务包装在任务中的 Async Blazor 事件过于复杂。

    @page "/Test"
    <input type="text" placeholder="Enter a Value" @bind-value="InputValue" @oninput="this.Filter" />
    <label for="modal_table_autosearch">Search by name</label>
    
    <button type="button" @onclick="() => this.Filter(new ChangeEventArgs { Value= null }))">
        Clear Value
    </button>
    @code {
    
        private string? InputValue { get; set; }
    
        protected async Task Filter(ChangeEventArgs args)
        {
            if (args.Value is null)
            {
                InputValue = null;
                // this.SetFilteringCollections();
                return;
            }
            var searchValue = args.Value?.ToString();
            // simulate some async work
            await Task.Delay(1000);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2021-11-20
      • 2013-08-15
      • 1970-01-01
      • 2018-06-25
      • 2015-04-22
      相关资源
      最近更新 更多