gpt4 book ai didi

用于过滤击键的 Blazor 组件

转载 作者:行者123 更新时间:2023-12-05 09:26:10 30 4
gpt4 key购买 nike

Blazor 有 InputNumber将输入限制为数字的组件。然而,这呈现了一个 <input type=number .../> firefox 不尊重(它允许任何文本)。

所以我尝试创建一个过滤输入的自定义组件:

@inherits InputNumber<int?>

<input type="number" @bind=_value @onkeypress=OnKeypress />
<p>@_value</p>

@code {
private string _value;

private void OnKeypress(KeyboardEventArgs e) {
if (Regex.IsMatch(e.Key, "[0-9]"))
_value += e.Key;
}
}

<p>显示正确的值。但输入本身会显示所有按键。

如何编写自定义组件来过滤击键? (在这个例子中,我过滤数字,但我假设相同的方法适用于过滤任何字符。)

最佳答案

如果您想使用 Blazor EditForm 基础结构,您可以创建自定义 InputNumber

以下代码继承自 InputNumber 并进行了以下更改。我已经使用 Firefox 和 Edge 对其进行了测试,但我的笔记本电脑上没有安装 Chrome。

  1. 输入类型更改为文本。这可确保所有浏览器的行为一致 - 如果设置为“数字”则不会如此。
  2. 输入 value 被映射到一个新的内部字段,该字段将从新的 setter 更新。
  3. oninput 连接到 SetValue 以捕获每个按键。
  4. SetValue 包含检查有效数字输入的新逻辑。代码有内嵌注释。
@inherits InputNumber<TValue>
@typeparam TValue

<input type="text"
value="@this.displayValue"
class="@this.CssClass"
@oninput=SetValue
@attributes=this.AdditionalAttributes
@ref=this.Element />

@code {
// create a unique string based on the null Ascii char
//private static string emptyString = ((char)0).ToString();
private static string emptyString = string.Empty;
private string? displayValue;

public async Task SetValue(ChangeEventArgs e)
{
// Get the current typed value
var value = e.Value?.ToString();

// Check if it's a number of the TValue or null
var isValidNumber = BindConverter.TryConvertTo<TValue>(value, System.Globalization.CultureInfo.CurrentCulture, out var num)
|| value is null;

// If it's not valid we need to reset the value
if (!isValidNumber)
{
// Set the value to an empty string
displayValue = emptyString;
// Call state has changed to render the component
StateHasChanged();
// Give thw renderer some processor time to execute the queued render by creating a Task continuation
await Task.Delay(1);
// Set the display to the previous value stored in CurrentValue
displayValue = FormatValueAsString(CurrentValue);
// done
return;
}

// We have a numbr so set the two fields to the current value
// This is the display value
displayValue = value;
// This triggers the full InputBase/EditContext logic
CurrentValueAsString = value;
}
}

为什么我们需要双渲染技巧

如果数字无效,我们必须双重渲染以修复实际 DOM 和渲染器 DOM 之间发生的不一致。

考虑一下:

  1. 当前值为 12。
  2. 渲染器的 DOM 段是 value="12"
  3. 我们将输入更改为 12q
  4. 浏览器 DOM 现在是 value="12q",而渲染器 DOM 仍然是 value="12"

如果我们现在将 Renderer DOM 设置为 value="12" 它没有改变。 Diffing 引擎看不出有什么不同,也不会更新浏览器 UI。

要解决这个问题,我们必须确保在将渲染器的 DOM 设置为原始值之前将其设置为其他内容。我们将其设置为空字符串,使用 Task.Delay 为渲染器提供一些处理器时间来实际渲染组件,然后最终将其设置回原始设置。

关于用于过滤击键的 Blazor 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74195088/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com