【问题标题】:Is there a way to use both @onfocus and HTML focus in Blazor without JavaScript?有没有办法在没有 JavaScript 的情况下在 Blazor 中同时使用 @onfocus 和 HTML 焦点?
【发布时间】:2021-05-18 12:26:44
【问题描述】:

我对 Blazor 还很陌生,但是当元素获得焦点时,我需要选择整个输入字段。

在 HTML 中,我可以使用这个:

<input onfocus="this.select();">

但问题是:我已经有一个绑定到 @onfocus 事件的 Blazor 方法:

<input @onfocus="@OnFocus"

我不能同时使用它们,因为我在 Visual Studio 中收到以下错误:

这意味着我需要找到一种在 OnFocus() 方法中以某种方式选择输入字段的方法。我知道我可以使用 JavaScript (JSInterop) 解决这个问题,但我希望有一种方法可以在不使用 JavaScript 的情况下做到这一点。

当前 OnFocus() 方法:

private void OnFocus (FocusEventArgs e) {
   if (String.IsNullOrEmpty(this.inputValue)) {
     this.inputValue = Utils.SetDefaultValue();
   }
   Utils.SelectInput(this.index); <-- current working JSInterop method I want to get rid off
}

【问题讨论】:

  • 你能解释一下为什么你不想使用JSInterop吗? AFAIK 实际上存在这样的情况。恕我直言,使用它本身并没有什么错……我的意思是,你还在使用 HTML 和 CSS……一切都有它的任务和目的……
  • 我是我公司的一名研究员,我的任务是在不使用过多 JavaScript 的情况下使用 Blazor 重新创建客户端。我知道有些功能需要用 JSInterop 来完成,但如果可以用 C# 和 HTML 来完成,那是首选。

标签: c# html blazor blazor-webassembly


【解决方案1】:

我想这应该可行:

<input @bind="Value" @onfocus ="@((FocusEventArgs args) =>  OnFocus(args))" onfocusin="this.select();">

@code
    {
private string Value { get; set; } = "MyValue";


private void OnFocus(FocusEventArgs e)
{
    
 }
}

有没有办法在没有 JavaScript 的情况下在 Blazor 中同时使用 @onfocus 和 HTML 焦点?

注意:@onfocus 是一个编译器指令,它创建如下代码:

__builder.AddAttribute(6, "onfocus", 
EventCallback.Factory.Create<FocusEventArgs>(this, (FocusEventArgs args) =>  OnFocus(args) ));

如您所见,这段代码在渲染时会附加一个事件处理程序到 JS“onfocus”事件,这就是为什么您不能使用它两次(导致错误)。 focus 或者更确切地说是 focus(),是一个被调用来设置焦点的方法,就像 select 是一个被调用来选择文本的方法一样。

请注意,您可以使用@onfocus 创建一个事件处理程序,您可以从中调用 JS 函数来选择代码。这是合法的。

【讨论】:

  • 谢谢!从来没有想过使用'onfocusin'属性:)
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多