首页 > 解决方案 > 无法制作嵌套组件

问题描述

抱歉,如果问题与我缺乏经验有关。我正在尝试制作一个组件库来处理来自 blazor 的地图框。现在我有一个主要组件 MapBoxView,它显示地图和 MapboxGeocoder,用于查找对象。每个组件在主组件 OnFirstAfterRenderAsync() 中都有一个过程:

protected async override Task OnFirstAfterRenderAsync()
{
    await base.OnFirstAfterRenderAsync();
    Dictionary<string, object> o = new Dictionary<string, object>();
    ...
    await JsInvokeAsync<object>("mapgl.mymap.initMap", o);
}

在嵌套组件中:

protected async override Task OnFirstAfterRenderAsync()
{
    await base.OnFirstAfterRenderAsync();
    Dictionary<string, object> o = new Dictionary<string, object>();
    o.Add("container", container);
    await JsInvokeAsync<object>("mapgl.mygeocoder.initGeocoder", o);
}

在演示程序中我使用代码:

@page "/"

<MapBoxView zoom=@_zoom container=@containerName mapCenter=@centerOfView>
</MapBoxView>

<MapBoxGeocoder Id="geocoder">
</MapBoxGeocoder>

然后一切正常,我得到了我想要的图片:在此处输入图像描述

在演示程序中我使用代码:

<MapBoxView zoom=@_zoom container=@containerName mapCenter=@centerOfView>
    <MapBoxGeocoder Id="geocoder">
    </MapBoxGeocoder>
</MapBoxView>

也就是说,我把嵌套组件放在主组件中,然后地理编码器(左下角有文本的窗口 - 图片上的搜索)没有显示,程序没有进入 MapBoxGeocoder 组件的 OnFirstAfterRenderAsync() 过程。主要组件 MapBoxView 有剃须刀代码:

@namespace MapBoxBlazor

@inherits BaseMapBoxView

    <div id='mapContainer'>
    </div>

我究竟做错了什么?怎么做才对?

标签: blazor

解决方案


您应该查看有关ChildContent的文档。

您需要使用RenderFragment命名ChildContent来允许您渲染嵌套组件。

父组件必须有属性

public RenderFragment ChildContent { get; set; }

并将其呈现在您想要的位置。例如

<div> 
    @ChildContent
</div>

此属性将渲染父组件内的所有内容。

所以对于你的情况,MapBoxView应该有ChildContent它并在里面渲染它才能工作。


推荐阅读