以下可路由组件防止用户清空输入框。这正是我想要的。
@page "/"
@using System.Text.RegularExpressions
<p>Counter: @counter</p>
<input
type="number"
@bind="counter"
@bind:event="oninput"
@onkeypress="OnKeyPress"
@onkeypress:preventDefault="true" />
@code {
private int counter;
private void OnKeyPress(KeyboardEventArgs e)
{
if (e.Key == "+")
counter++;
else if (e.Key == "-")
counter--;
if (Regex.IsMatch(e.Key, "[0-9]"))
{
counter = int.Parse($"{counter}{e.Key}");
}
}
}
由于某些原因,我必须绑定但不绑定@bind
和@bind:event
,如下所示。
@page "/"
@using System.Text.RegularExpressions
<p>Counter: @counter</p>
<input
type="number"
value="@counter"
@oninput="OnInput"
@onkeypress="OnKeyPress"
@onkeypress:preventDefault="true" />
@code {
private int counter;
private void OnInput(ChangeEventArgs e)
{
if(e.Value.ToString() == string.Empty)
{
e.Value = "0";
counter = int.Parse(e.Value.ToString());
}
}
private void OnKeyPress(KeyboardEventArgs e)
{
if (e.Key == "+")
counter++;
else if (e.Key == "-")
counter--;
if (Regex.IsMatch(e.Key, "[0-9]"))
{
counter = int.Parse($"{counter}{e.Key}");
}
}
}
但是,不再阻止用户清空输入框。
问题
如何防止用户清空输入框而不使用@bind
和@bind:event
?
这比其他答案要好得多,包括使用减号和加号键:
@page "/"
@using System.Text.RegularExpressions
<input type="number"
value="@counter"
@oninput="EventCallback.Factory.CreateBinder<int>(this, __value => counter = __value, counter)"
@onkeydown="OnKeyDown"
@onkeypress="OnKeyPress"
@onkeypress:preventDefault="true" />
@code {
private int counter;
private void OnKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Backspace" && (counter.ToString().Length == 1))
{
counter = 1;
return;
}
}
private void OnKeyPress(KeyboardEventArgs e)
{
if (e.Key == "+")
counter++;
else if (e.Key == "-")
counter--;
if (Regex.IsMatch(e.Key, "[0-9]"))
{
counter = int.Parse($"{counter}{e.Key}");
}
}
}
以下版本将输入作为字符串而不是数字进行操作。这实际上就是输入类型号内部的工作方式。总的来说,除了这个版本使用字符串而不是数值之外,这两个版本之间没有太大的区别。
@page "/"
@using System.Text.RegularExpressions
<input type="number"
value="@counter"
@oninput="OnInput"
@onkeydown="OnKeyDown"
@onkeypress="OnKeyPress"
@onkeypress:preventDefault="true" />
<input type="number" />
@code {
private string counter = "0";
private void OnInput(ChangeEventArgs args)
{
if (args.Value.ToString() == "")
{
counter = "0";
}
else
{
counter = args.Value.ToString();
}
}
private void OnKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Backspace" && counter.Length == 1)
{
// Note that I'm using here space, but you may use any
// character and string as long as it is not "0".
counter = " ";
}
}
private void OnKeyPress(KeyboardEventArgs e)
{
if (e.Key == "+")
{
var num = int.Parse(counter.ToString());
num++;
counter = num.ToString();
}
else if (e.Key == "-")
{
var num = int.Parse(counter.ToString());
num--;
counter = num.ToString();
}
if (Regex.IsMatch(e.Key, "[0-9]"))
{
counter += int.Parse($"{e.Key}").ToString();
}
}
}