在Blazor中,如何动态更改HTML标签? [英] In Blazor, how can I dynamically change an HTML tag?

查看:41
本文介绍了在Blazor中,如何动态更改HTML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的Blazor组件中具有以下标记:

Let's say I have the following markup in my Blazor component:

<div @attributes=Attributes data-myattr="something">
    @ChildContent
</div>

我想为父组件提供一种方法来确定将使用哪个标签代替< div> .像这样:

I'd like to provide a way for the parent component to determine which tag is going to be used in place of <div>. Something like:

<@Tag @attributes=Attributes data-myattr="something">
    @ChildContent
</@Tag>

@Tag为字符串参数.当然,这是行不通的.我知道模板,但是它对我不起作用,因为我想控制标签的结构,并为其添加额外的属性.我只想让用户选择要显示哪个标签.

With @Tag being a string Parameter. Of course that doesn't work. I'm aware of templates but it doesn't work for me because I want to be in control the structure of the tag, and add extra attributes to it. I just want to give the user a choice of which tag is going to be displayed.

推荐答案

不是创建.razor文件,而是创建.cs文件.

Instead of having a .razor file create a .cs file.

在文件中创建您的类公共类MyComponent:ComponentBase

,然后覆盖BuildRenderTree

and then override BuildRenderTree

protected override void BuildRenderTree(RenderTreeBuilder builder)
{
  builder.OpenElement(0, YourParameter);
  builder.CloseElement();
}

如果您不确定如何使用RenderTreeBuilder,只需创建一个临时剃刀文件并创建所需的标记,然后在 obj \ Debug \ netstandard2.1 \ Razor \

If you don't know exactly how to use the RenderTreeBuilder, simply create a temporary razor file and create the markup you want, then look in obj\Debug\netstandard2.1\Razor\

如果要在 .razor 文件中实现此目的,则可以按照以下步骤创建一个组件

If you want to achieve this in a .razor file then you can create a component like this following

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BlazorApp118.Shared
{
    public class Dynamic : ComponentBase
    {
        [Parameter]
        public string Tag { get; set; }

        [Parameter]
        public Dictionary<string, object> AdditionalAttributes { get; set; }

        [Parameter]
        public RenderFragment ChildContent { get; set; }

        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            if (string.IsNullOrWhiteSpace(Tag))
                throw new ArgumentNullException(nameof(Tag));

            builder.OpenElement(0, Tag);
            if (AdditionalAttributes?.Any() == true)
                builder.AddMultipleAttributes(1, AdditionalAttributes);
            if (ChildContent != null)
                builder.AddContent(2, ChildContent);
            builder.CloseElement();
        }
    }
}

然后像这样使用它

<Dynamic Tag="a" AdditionalAttributes=@SomeDictionaryOfValues>
  Any content you want here
</Dynamic>

这篇关于在Blazor中,如何动态更改HTML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆