Blazor提供了数据绑定语法用于绑定组件状态变量和事件,这篇笔记我们学习Blazor数据绑定相关的知识。
Blazor组件中,我们可以绑定组件状态变量到模板内,对于输入型的组件如<input>
,我们还可以实现双向绑定。
下面例子将text
变量的值绑定到了<input>
的value
属性。
@rendermode InteractiveServer
<input value="@text" />
@code {
private string text = "hello";
}
下面例子对<input>
和text
变量进行了双向绑定,此时输入框的内容改变时,<div>@text</div>
的内容也会随之改变。
@rendermode InteractiveServer
<input @bind="text" />
<div>@text</div>
@code {
private string? text;
}
Blazor对各种HTML元素提供了事件绑定语法,例如对于按钮我们可以使用@onclick
绑定按钮点击事件,下面是一个例子。
@rendermode InteractiveServer
<button @onclick="HandleButtonClick">Click me</button>
@code {
private void HandleButtonClick()
{
Console.WriteLine("Button clicked");
}
}
@
符号的说明数据绑定中,@
符号的用法可能有点迷惑性,value="@text"
和@bind="text"
如何区分@
该放在那里?实际上是这样理解的,value="@text"
中value
是一个HTML属性(HTML和Razor语法都没有@value
这种东西),而@text
引用一个变量,将其传递给HTML的value
属性。至于@bind="text"
中,@bind
是Blazor提供的用于双向绑定的语法,它接收一个状态变量名,因此我们将text
传递给了它,而不能写作@text
。