RenderFragmentExample1.razor
This component emits the fragment defined by the ChildContent
parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@typeparam TItem @if (Items != null) { <ul> @foreach(TItem item in Items) { @ChildContent(item) } </ul> } @code { [Parameter] public IEnumerable<TItem>? Items { get; set; } [Parameter] public RenderFragment<TItem> ChildContent { get; set; } } |
Parent component using the component above
Note the two ways to use RenderFragmentExample1
. In the first use, the implicit context is provided with code>@ChildContent</code as a bound field (ie, not as a tag). The code>@ChildContent</code value works only for components with a single RenderFragment
parameter.
The second example is more explicit, using ChildContent
as a tag with a Context
attribute. Defining fragment parameters this way is required for components with more than one RenderFragment
parameter (and to my eyes makes more sense).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@page "/" <PageTitle>Context Example</PageTitle> <ComponentWithoutContext Items=@people> <li>@context.Name, @context.Age</li?> </ComponentWithoutContext> <ComponentWithContext Items=@people> <ChildContent Context="person"> <li>@person.Name @person.Age</li> </ChildContent> </ComponentWithContext> @code { public IEnumerable<Person> people; protected override void OnInitialized() { base.OnInitialized(); this.people = new Person[] { new Person {Id=1, Name="John", Age=44}, new Person {Id=2, Name="George", Age=43}, new Person {Id=3, Name="Ringo", Age=42}, new Person {Id=4, Name="Paul", Age=41} }; } } |