Composants ASP.NET Core Razor rendus dynamiquement
Remarque
Ceci n’est pas la dernière version de cet article. Pour la version actuelle, consultez la version .NET 8 de cet article.
Avertissement
Cette version d’ASP.NET Core n’est plus prise en charge. Pour plus d’informations, consultez la Stratégie de prise en charge de .NET et .NET Core. Pour la version actuelle, consultez la version .NET 8 de cet article.
Important
Ces informations portent sur la préversion du produit, qui est susceptible d’être en grande partie modifié avant sa commercialisation. Microsoft n’offre aucune garantie, expresse ou implicite, concernant les informations fournies ici.
Pour la version actuelle, consultez la version .NET 8 de cet article.
Par Dave Brock
Utilisez le composant DynamicComponent intégré pour restituer les composants par type.
Composants dynamiques
Un DynamicComponent est utile pour le rendu des composants sans itérer par le biais de types possibles ou à l’aide d’une logique conditionnelle. Par exemple, DynamicComponent peut restituer un composant en fonction d’une sélection d’utilisateur dans une liste déroulante.
Dans l’exemple suivant :
componentType
spécifie le type.parameters
spécifie les paramètres de composant à passer au composantcomponentType
.
<DynamicComponent Type="componentType" Parameters="parameters" />
@code {
private Type componentType = ...;
private IDictionary<string, object> parameters = ...;
}
Pour plus d’informations sur la transmission de valeurs de paramètres, consultez la section Passer des paramètres plus loin dans cet article.
Exemple
Dans l’exemple suivant, un composant Razor affiche un composant en fonction de la sélection de l’utilisateur dans une liste déroulante de quatre valeurs possibles.
Sélection de vaisseau utilisateur | Composant Razor partagé à restituer |
---|---|
Rocket Lab® | RocketLab.razor |
SpaceX® | SpaceX.razor |
ULA® | UnitedLaunchAlliance.razor |
Virgin Galactic® | VirginGalactic.razor |
RocketLab.razor
:
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
SpaceX.razor
:
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
UnitedLaunchAlliance.razor
:
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
VirginGalactic.razor
:
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
DynamicComponent1.razor
:
@page "/dynamic-component-1"
<PageTitle>Dynamic Component 1</PageTitle>
<h1>Dynamic Component Example 1</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var entry in components.Keys)
{
<option value="@entry">@entry</option>
}
</select>
</label>
</p>
@if (selectedType is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedType" />
</div>
}
@code {
private readonly Dictionary<string, Type> components = new()
{
["Rocket Lab"] = typeof(RocketLab),
["SpaceX"] = typeof(SpaceX),
["ULA"] = typeof(UnitedLaunchAlliance),
["Virgin Galactic"] = typeof(VirginGalactic)
};
private Type? selectedType;
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) &&
!String.IsNullOrWhiteSpace(dropdownValue))
{
selectedType = components[dropdownValue];
}
else
{
selectedType = null;
}
}
}
RocketLab.razor
:
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
SpaceX.razor
:
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
UnitedLaunchAlliance.razor
:
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
VirginGalactic.razor
:
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
DynamicComponent1.razor
:
@page "/dynamic-component-1"
<PageTitle>Dynamic Component 1</PageTitle>
<h1>Dynamic Component Example 1</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var entry in components.Keys)
{
<option value="@entry">@entry</option>
}
</select>
</label>
</p>
@if (selectedType is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedType" />
</div>
}
@code {
private readonly Dictionary<string, Type> components = new()
{
["Rocket Lab"] = typeof(RocketLab),
["SpaceX"] = typeof(SpaceX),
["ULA"] = typeof(UnitedLaunchAlliance),
["Virgin Galactic"] = typeof(VirginGalactic)
};
private Type? selectedType;
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) &&
!String.IsNullOrWhiteSpace(dropdownValue))
{
selectedType = components[dropdownValue];
}
else
{
selectedType = null;
}
}
}
RocketLab.razor
:
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
SpaceX.razor
:
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
UnitedLaunchAlliance.razor
:
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
VirginGalactic.razor
:
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
DynamicComponentExample1.razor
:
@page "/dynamiccomponent-example-1"
<h1><code>DynamicComponent</code> Component Example 1</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var entry in components.Keys)
{
<option value="@entry">@entry</option>
}
</select>
</label>
</p>
@if (selectedType is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedType" />
</div>
}
@code {
private readonly Dictionary<string, Type> components = new()
{
["Rocket Lab"] = typeof(RocketLab),
["SpaceX"] = typeof(SpaceX),
["ULA"] = typeof(UnitedLaunchAlliance),
["Virgin Galactic"] = typeof(VirginGalactic)
};
private Type? selectedType;
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedType = components[dropdownValue];
}
else
{
selectedType = null;
}
}
}
RocketLab.razor
:
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
SpaceX.razor
:
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
UnitedLaunchAlliance.razor
:
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
VirginGalactic.razor
:
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
DynamicComponentExample1.razor
:
@page "/dynamiccomponent-example-1"
<h1><code>DynamicComponent</code> Component Example 1</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var entry in components.Keys)
{
<option value="@entry">@entry</option>
}
</select>
</label>
</p>
@if (selectedType is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedType" />
</div>
}
@code {
private readonly Dictionary<string, Type> components = new()
{
["Rocket Lab"] = typeof(RocketLab),
["SpaceX"] = typeof(SpaceX),
["ULA"] = typeof(UnitedLaunchAlliance),
["Virgin Galactic"] = typeof(VirginGalactic)
};
private Type? selectedType;
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedType = components[dropdownValue];
}
else
{
selectedType = null;
}
}
}
Dans l'exemple précédent :
- Il Dictionary<TKey,TValue> est utilisé pour gérer les composants à afficher.
- Les noms servent de clés de dictionnaire et sont fournis comme options de sélection.
- Les types de composants sont stockés en tant que valeurs de dictionnaire à l’aide de l’opérateur
typeof
.
Passer des paramètres
Si les composants rendus dynamiquement ont des paramètres de composant, passez-les dans le DynamicComponent en tant que IDictionary<string, object>
. La string
est le nom du paramètre et la object
est la valeur du paramètre.
L’exemple suivant configure un objet de métadonnées de composant (ComponentMetadata
) pour fournir des valeurs de paramètre aux composants rendus dynamiquement en fonction du nom de type. L’exemple n’est qu’une des nombreuses approches que vous pouvez adopter. Des données de paramètre peuvent également être fournies à partir d’une API web, d’une base de données ou d’une méthode. La seule exigence est que l’approche retourne un IDictionary<string, object>
.
ComponentMetadata.cs
:
namespace BlazorSample;
public class ComponentMetadata
{
public required Type Type { get; init; }
public required string Name { get; init; }
public Dictionary<string, object> Parameters { get; } = [];
}
namespace BlazorSample;
public class ComponentMetadata
{
public required Type Type { get; init; }
public required string Name { get; init; }
public Dictionary<string, object> Parameters { get; } = [];
}
public class ComponentMetadata
{
public required Type Type { get; init; }
public required string Name { get; init; }
public Dictionary<string, object> Parameters { get; } = new();
}
public class ComponentMetadata
{
public Type? Type { get; init; }
public string? Name { get; init; }
public Dictionary<string, object> Parameters { get; } = new();
}
Le composant RocketLabWithWindowSeat
suivant (RocketLabWithWindowSeat.razor
) a été mis à jour à partir de l’exemple précédent pour inclure un paramètre de composant nommé WindowSeat
pour spécifier si le passager préfère un siège côté fenêtre sur son vol :
RocketLabWithWindowSeat.razor
:
<h2>Rocket Lab®</h2>
<p>
User selected a window seat: @WindowSeat
</p>
<p>
Rocket Lab is a trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
[Parameter]
public bool WindowSeat { get; set; }
}
<h2>Rocket Lab®</h2>
<p>
User selected a window seat: @WindowSeat
</p>
<p>
Rocket Lab is a trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
[Parameter]
public bool WindowSeat { get; set; }
}
<h2>Rocket Lab®</h2>
<p>
User selected a window seat: @WindowSeat
</p>
<p>
Rocket Lab is a trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
[Parameter]
public bool WindowSeat { get; set; }
}
<h2>Rocket Lab®</h2>
<p>
User selected a window seat: @WindowSeat
</p>
<p>
Rocket Lab is a trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
[Parameter]
public bool WindowSeat { get; set; }
}
Dans l’exemple suivant :
- Seul le paramètre du composant
RocketLabWithWindowSeat
pour un siège côté fenêtre (WindowSeat
) reçoit la valeur de la caseWindow Seat
. - Les noms de composant sont utilisés comme valeurs d’option à l’aide de l’opérateur
nameof
, qui retourne les noms de composant sous forme de chaînes constantes. - Les composants rendus dynamiquement sont des composants partagés :
- Illustré dans cette section de l’article :
RocketLabWithWindowSeat
(RocketLabWithWindowSeat.razor
) - Composants présentés dans la section Exemple plus haut dans cet article :
SpaceX
(SpaceX.razor
)UnitedLaunchAlliance
(UnitedLaunchAlliance.razor
)VirginGalactic
(VirginGalactic.razor
)
- Illustré dans cette section de l’article :
DynamicComponent2.razor
:
@page "/dynamic-component-2"
<PageTitle>Dynamic Component 2</PageTitle>
<h1>Dynamic Component Example 2</h1>
<p>
<label>
<input type="checkbox" @bind="windowSeat"
@bind:after="HandleWindowSeatChanged" />
Window Seat (Rocket Lab only)
</label>
</p>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
@code {
private Dictionary<string, ComponentMetadata> components =
new()
{
[nameof(RocketLabWithWindowSeat)] = new ComponentMetadata()
{
Type = typeof(RocketLabWithWindowSeat),
Name = "Rocket Lab with Window Seat",
Parameters = { [nameof(RocketLabWithWindowSeat.WindowSeat)] = false }
},
[nameof(VirginGalactic)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic),
Name = "Virgin Galactic"
},
[nameof(UnitedLaunchAlliance)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance),
Name = "ULA"
},
[nameof(SpaceX)] = new ComponentMetadata()
{
Type = typeof(SpaceX),
Name = "SpaceX"
}
};
private ComponentMetadata? selectedComponent;
private bool windowSeat;
private void HandleWindowSeatChanged()
{
components[nameof(RocketLabWithWindowSeat)]
.Parameters[nameof(RocketLabWithWindowSeat.WindowSeat)] = windowSeat;
}
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
}
DynamicComponent2.razor
:
@page "/dynamic-component-2"
<PageTitle>Dynamic Component 2</PageTitle>
<h1>Dynamic Component Example 2</h1>
<p>
<label>
<input type="checkbox" @bind="windowSeat"
@bind:after="HandleWindowSeatChanged" />
Window Seat (Rocket Lab only)
</label>
</p>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
@code {
private Dictionary<string, ComponentMetadata> components =
new()
{
[nameof(RocketLabWithWindowSeat)] = new ComponentMetadata()
{
Type = typeof(RocketLabWithWindowSeat),
Name = "Rocket Lab with Window Seat",
Parameters = { [nameof(RocketLabWithWindowSeat.WindowSeat)] = false }
},
[nameof(VirginGalactic)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic),
Name = "Virgin Galactic"
},
[nameof(UnitedLaunchAlliance)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance),
Name = "ULA"
},
[nameof(SpaceX)] = new ComponentMetadata()
{
Type = typeof(SpaceX),
Name = "SpaceX"
}
};
private ComponentMetadata? selectedComponent;
private bool windowSeat;
private void HandleWindowSeatChanged()
{
components[nameof(RocketLabWithWindowSeat)]
.Parameters[nameof(RocketLabWithWindowSeat.WindowSeat)] = windowSeat;
}
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
}
DynamicComponentExample2.razor
:
@page "/dynamiccomponent-example-2"
<h1><code>DynamicComponent</code> Component Example 2</h1>
<p>
<label>
<input type="checkbox" @bind="windowSeat" @bind:after="HandleWindowSeatChanged" />
Window Seat (Rocket Lab only)
</label>
</p>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
@code {
private Dictionary<string, ComponentMetadata> components =
new()
{
[nameof(RocketLabWithWindowSeat)] = new ComponentMetadata()
{
Type = typeof(RocketLabWithWindowSeat),
Name = "Rocket Lab with Window Seat",
Parameters = { [nameof(RocketLabWithWindowSeat.WindowSeat)] = false }
},
[nameof(VirginGalactic)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic),
Name = "Virgin Galactic"
},
[nameof(UnitedLaunchAlliance)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance),
Name = "ULA"
},
[nameof(SpaceX)] = new ComponentMetadata()
{
Type = typeof(SpaceX),
Name = "SpaceX"
}
};
private ComponentMetadata? selectedComponent;
private bool windowSeat;
private void HandleWindowSeatChanged()
{
components[nameof(RocketLabWithWindowSeat)]
.Parameters[nameof(RocketLabWithWindowSeat.WindowSeat)] = windowSeat;
}
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
}
DynamicComponentExample2.razor
:
@page "/dynamiccomponent-example-2"
<h1><code>DynamicComponent</code> Component Example 2</h1>
<p>
<label>
<input type="checkbox" @bind="WindowSeat" />
Window Seat (Rocket Lab only)
</label>
</p>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
@code {
private Dictionary<string, ComponentMetadata> components =
new()
{
[nameof(RocketLabWithWindowSeat)] = new ComponentMetadata()
{
Type = typeof(RocketLabWithWindowSeat),
Name = "Rocket Lab with Window Seat",
Parameters = { [nameof(RocketLabWithWindowSeat.WindowSeat)] = false }
},
[nameof(VirginGalactic)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic),
Name = "Virgin Galactic"
},
[nameof(UnitedLaunchAlliance)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance),
Name = "ULA"
},
[nameof(SpaceX)] = new ComponentMetadata()
{
Type = typeof(SpaceX),
Name = "SpaceX"
}
};
private ComponentMetadata? selectedComponent;
private bool windowSeat;
private bool WindowSeat
{
get { return windowSeat; }
set
{
windowSeat = value;
components[nameof(RocketLabWithWindowSeat)]
.Parameters[nameof(RocketLabWithWindowSeat.WindowSeat)] = windowSeat;
}
}
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
}
Rappels d’événements (EventCallback
)
Les rappels d’événements (EventCallback) peuvent être passés à un DynamicComponent dans son dictionnaire de paramètres.
ComponentMetadata.cs
:
namespace BlazorSample;
public class ComponentMetadata
{
public required Type Type { get; init; }
public required string Name { get; init; }
public Dictionary<string, object> Parameters { get; } = [];
}
namespace BlazorSample;
public class ComponentMetadata
{
public required Type Type { get; init; }
public required string Name { get; init; }
public Dictionary<string, object> Parameters { get; } = [];
}
public class ComponentMetadata
{
public required Type Type { get; init; }
public required string Name { get; init; }
public Dictionary<string, object> Parameters { get; } = new();
}
public class ComponentMetadata
{
public Type? Type { get; init; }
public string? Name { get; init; }
public Dictionary<string, object> Parameters { get; } = new();
}
Implémentez un paramètre de rappel d’événement (EventCallback) dans chaque composant rendu dynamiquement.
RocketLab2.razor
:
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
SpaceX2.razor
:
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>SpaceX®</h2>
<p>
SpaceX is a registered trademark of
<a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a>
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
UnitedLaunchAlliance2.razor
:
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>United Launch Alliance®</h2>
<p>
United Launch Alliance and ULA are registered trademarks of
<a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
VirginGalactic2.razor
:
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
<h2>Virgin Galactic®</h2>
<p>
Virgin Galactic is a registered trademark of
<a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>.
</p>
<button @onclick="OnClickCallback">
Trigger a Parent component method
</button>
@code {
[Parameter]
public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
Dans l’exemple de composant parent suivant, la méthode ShowDTMessage
affecte une chaîne avec l’heure actuelle à message
, et la valeur de message
est rendue.
Le composant parent transmet la méthode de rappel, ShowDTMessage
, dans le dictionnaire de paramètres :
- La clé
string
est le nom de la méthode de rappel,OnClickCallback
. - La valeur
object
est créée par EventCallbackFactory.Create pour la méthode de rappel parent,ShowDTMessage
. Notez que le mot cléthis
n’est pas pris en charge dans les champs C#. Par conséquent, une propriété C# est utilisée pour le dictionnaire de paramètres.
DynamicComponent3.razor
:
@page "/dynamic-component-3"
<PageTitle>Dynamic Component 3</PageTitle>
<h1>Dynamic Component Example 3</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in Components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
<p>
@message
</p>
@code {
private ComponentMetadata? selectedComponent;
private string? message;
private Dictionary<string, ComponentMetadata> Components =>
new()
{
[nameof(RocketLab2)] = new ComponentMetadata()
{
Type = typeof(RocketLab2),
Name = "Rocket Lab",
Parameters = { [nameof(RocketLab2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(VirginGalactic2)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic2),
Name = "Virgin Galactic",
Parameters = { [nameof(VirginGalactic2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(UnitedLaunchAlliance2)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance2),
Name = "ULA",
Parameters = { [nameof(UnitedLaunchAlliance2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(SpaceX2)] = new ComponentMetadata()
{
Type = typeof(SpaceX2),
Name = "SpaceX",
Parameters = { [nameof(SpaceX2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
}
};
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = Components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
private void ShowDTMessage(MouseEventArgs e) =>
message = $"The current DT is: {DateTime.Now}.";
}
DynamicComponent3.razor
:
@page "/dynamic-component-3"
<PageTitle>Dynamic Component 3</PageTitle>
<h1>Dynamic Component Example 3</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in Components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
<p>
@message
</p>
@code {
private ComponentMetadata? selectedComponent;
private string? message;
private Dictionary<string, ComponentMetadata> Components =>
new()
{
[nameof(RocketLab2)] = new ComponentMetadata()
{
Type = typeof(RocketLab2),
Name = "Rocket Lab",
Parameters = { [nameof(RocketLab2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(VirginGalactic2)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic2),
Name = "Virgin Galactic",
Parameters = { [nameof(VirginGalactic2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(UnitedLaunchAlliance2)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance2),
Name = "ULA",
Parameters = { [nameof(UnitedLaunchAlliance2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(SpaceX2)] = new ComponentMetadata()
{
Type = typeof(SpaceX2),
Name = "SpaceX",
Parameters = { [nameof(SpaceX2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
}
};
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = Components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
private void ShowDTMessage(MouseEventArgs e) =>
message = $"The current DT is: {DateTime.Now}.";
}
DynamicComponentExample3.razor
:
@page "/dynamiccomponent-example-3"
<h1><code>DynamicComponent</code> Component Example 3</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in Components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
<p>
@message
</p>
@code {
private ComponentMetadata? selectedComponent;
private string? message;
private Dictionary<string, ComponentMetadata> Components =>
new()
{
[nameof(RocketLab2)] = new ComponentMetadata()
{
Type = typeof(RocketLab2),
Name = "Rocket Lab",
Parameters = { [nameof(RocketLab2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(VirginGalactic2)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic2),
Name = "Virgin Galactic",
Parameters = { [nameof(VirginGalactic2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(UnitedLaunchAlliance2)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance2),
Name = "ULA",
Parameters = { [nameof(UnitedLaunchAlliance2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(SpaceX2)] = new ComponentMetadata()
{
Type = typeof(SpaceX2),
Name = "SpaceX",
Parameters = { [nameof(SpaceX2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
}
};
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = Components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
private void ShowDTMessage(MouseEventArgs e) =>
message = $"The current DT is: {DateTime.Now}.";
}
DynamicComponentExample3.razor
:
@page "/dynamiccomponent-example-3"
<h1><code>DynamicComponent</code> Component Example 3</h1>
<p>
<label>
Select your transport:
<select @onchange="OnDropdownChange">
<option value="">Select a value</option>
@foreach (var c in Components)
{
<option value="@c.Key">@c.Value.Name</option>
}
</select>
</label>
</p>
@if (selectedComponent is not null)
{
<div class="border border-primary my-1 p-1">
<DynamicComponent Type="selectedComponent.Type"
Parameters="selectedComponent.Parameters" />
</div>
}
<p>
@message
</p>
@code {
private ComponentMetadata? selectedComponent;
private string? message;
private Dictionary<string, ComponentMetadata> Components =>
new()
{
[nameof(RocketLab2)] = new ComponentMetadata()
{
Type = typeof(RocketLab2),
Name = "Rocket Lab",
Parameters = { [nameof(RocketLab2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(VirginGalactic2)] = new ComponentMetadata()
{
Type = typeof(VirginGalactic2),
Name = "Virgin Galactic",
Parameters = { [nameof(VirginGalactic2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(UnitedLaunchAlliance2)] = new ComponentMetadata()
{
Type = typeof(UnitedLaunchAlliance2),
Name = "ULA",
Parameters = { [nameof(UnitedLaunchAlliance2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
},
[nameof(SpaceX2)] = new ComponentMetadata()
{
Type = typeof(SpaceX2),
Name = "SpaceX",
Parameters = { [nameof(SpaceX2.OnClickCallback)] =
EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) }
}
};
private void OnDropdownChange(ChangeEventArgs e)
{
if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue))
{
selectedComponent = Components[dropdownValue];
}
else
{
selectedComponent = null;
}
}
private void ShowDTMessage(MouseEventArgs e) =>
message = $"The current DT is: {DateTime.Now}.";
}
Éviter les paramètres fourre-tout
Évitez l’utilisation de paramètres fourre-tout. Si des paramètres fourre-tout sont utilisés, chaque paramètre explicite sur DynamicComponent est effectivement un mot réservé que vous ne pouvez pas passer à un enfant dynamique. Tous les nouveaux paramètres passés à DynamicComponent sont un changement cassant, car ils commencent à remplacer les paramètres de composant enfant qui portent le même nom. Il est peu probable que l’appelant connaisse toujours un ensemble fixe de noms de paramètres à passer à tous les enfants dynamiques possibles.
Accéder à l’instance de composant créée dynamiquement
Utilisez la propriété Instance pour accéder à l’instance de composant créée dynamiquement.
Créez une interface pour décrire l’instance du composant chargé dynamiquement, incluant toutes les méthodes et propriétés nécessaires auxquelles le composant parent doit accéder. L’exemple suivant spécifie une méthode Log
à implémenter dans les composants.
Interfaces/ILoggable.cs
:
using Microsoft.AspNetCore.Components;
namespace BlazorSample.Interfaces;
public interface ILoggable : IComponent
{
public void Log();
}
using Microsoft.AspNetCore.Components;
namespace BlazorSample.Interfaces;
public interface ILoggable : IComponent
{
public void Log();
}
using Microsoft.AspNetCore.Components;
namespace BlazorSample.Interfaces;
public interface ILoggable : IComponent
{
public void Log();
}
using Microsoft.AspNetCore.Components;
namespace BlazorSample.Interfaces;
public interface ILoggable : IComponent
{
public void Log();
}
Chaque définition de composant implémente l’interface. L’exemple suivant est un composant Rocket Lab® modifié de la section Exemple qui enregistre une chaîne via sa méthode Log
.
RocketLab3.razor
:
@using BlazorSample.Interfaces
@implements ILoggable
@inject ILogger<RocketLab3> Logger
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
public void Log() => Logger.LogInformation("Woot! I logged this call!");
}
@using BlazorSample.Interfaces
@implements ILoggable
@inject ILogger<RocketLab3> Logger
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
public void Log() => Logger.LogInformation("Woot! I logged this call!");
}
@using BlazorSample.Interfaces
@implements ILoggable
@inject ILogger<RocketLab3> Logger
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
public void Log()
{
Logger.LogInformation("Woot! I logged this call!");
}
}
@using BlazorSample.Interfaces
@implements ILoggable
@inject ILogger<RocketLab3> Logger
<h2>Rocket Lab®</h2>
<p>
Rocket Lab is a registered trademark of
<a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a>
</p>
@code {
public void Log()
{
Logger.LogInformation("Woot! I logged this call!");
}
}
Les trois autres composants partagés (VirginGalactic3
, UnitedLaunchAlliance3
, SpaceX3
) reçoivent un traitement similaire :
Les directives suivantes sont ajoutées aux composants, où l’espace réservé
{COMPONENT TYPE}
est le type de composant :@using BlazorSample.Interfaces @implements ILoggable @inject ILogger<{COMPONENT TYPE}> Logger
Chaque composant implémente une méthode
Log
. La catégorie de journal écrite par l’enregistreur d’événements inclut le nom complet du type de composant lorsque LogInformation est appelé :@code { public void Log() { Logger.LogInformation("Woot! I logged this call!"); } }
Le composant parent caste l’instance du composant chargé dynamiquement en tant que ILoggable
pour accéder aux membres de l’interface. Dans l’exemple suivant, la méthode Log
du composant chargé est appelée lorsqu’un bouton est sélectionné dans l’interface utilisateur :
...
@using BlazorSample.Interfaces
...
<DynamicComponent Type="..." @ref="dc" />
...
<button @onclick="LogFromLoadedComponent">Log from loaded component</button>
@code {
private DynamicComponent? dc;
...
private void LogFromLoadedComponent() => (dc?.Instance as ILoggable)?.Log();
}
Pour une démonstration fonctionnelle de l’exemple précédent, consultez le composant DynamicComponent4
dans l’application d’exemple Blazor.
Pour une démonstration fonctionnelle de l’exemple précédent, consultez le composant DynamicComponent4
dans l’application d’exemple Blazor.
Pour une démonstration fonctionnelle de l’exemple précédent, consultez le composant DynamicComponentExample4
dans l’application d’exemple Blazor.
Pour une démonstration fonctionnelle de l’exemple précédent, consultez le composant DynamicComponentExample4
dans l’application d’exemple Blazor.
Marques déposées
Rocket Lab est une marque déposée de Rocket Lab USA Inc. SpaceX est une marque déposée de Space Exploration Technologies Corp. United Launch Alliance et ULA sont des marques déposées de United Launch Alliance, LLC. Virgin Galactic est une marque déposée de Galactic Enterprises, LLC.