如何在blazor中点击按钮创建html表单?没有javascript有什么方法可以做到这一点吗?如果是,如何?如果不是


<button onclick="createForm">create form</button>
<form >
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form> 

我想在单击"创建表单"按钮时创建表单。开始时不会显示任何表单。就在单击"创建表单"按钮时。

最简单的方法是隐藏表单并在按钮的单击事件中显示。您可以使用简单的Razor Markup来实现这一点。

<button onclick="createForm">create form</button>
@if(IsFormVisible)
{
<form >
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form> 
}
@code
{
bool IsFormVisible = false;
void createForm()
{
IsFormVisible = true;
StateHasChanged();
}
}

第二种方法是使用.NET6附带的DynamicComponent(这可能有些过头了(。基本上,你可以创建任何组件,并将其作为参数传递给DynamicComponent,它将呈现你传递给它的组件

<DynamicComponent Type="@YourFormComponent"/>

有关详细信息,您可以参考Dave Brock的文章:https://www.daveabrock.com/2021/04/08/blazor-dynamic-component/

相关内容

最新更新