Components
Blazor components are the fundamental building blocks of Blazor applications. They are reusable pieces of UI, often defined as Razor components (.razor files), that encapsulate rendering logic and event handling.
Creating a Blazor Component
A Blazor component is typically defined in a file with a .razor
extension. This file combines HTML markup for the UI with C# code for logic and event handling.
Example: A Simple Counter Component
@page "/counter"
Counter
Current count: @currentCount
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Component Structure
A Razor component consists of:
- Markup: HTML and Blazor-specific syntax for rendering the UI.
- Code Block: Defined by the
@code
directive, containing C# properties, methods, and event handlers. - Directives: Special instructions like
@page
for routing or@inject
for dependency injection.
Component Parameters
Components can accept input parameters using the [Parameter]
attribute. This allows for data to be passed from parent components to child components.
Example: Component with Parameters
@* ParentComponent.razor *@
<h3>Welcome, @userName!</h3>
<GreetingMessage Message="Hello from parent!" User="Alice" />
@code {
private string userName = "Alice";
}
@* GreetingMessage.razor *@
<div>
<p>@Message</p>
<p>User: @User</p>
</div>
@code {
[Parameter]
public string Message { get; set; }
[Parameter]
public string User { get; set; }
}
Component Lifecycle
Blazor components have a defined lifecycle, with methods that are called at various stages (e.g., initialization, rendering, disposal). This allows you to hook into specific moments to perform actions.
Key lifecycle methods include:
OnInitializedAsync
: For asynchronous initialization.OnParametersSetAsync
: When component parameters have been set.ShouldRender
: To control whether the component should re-render.OnAfterRenderAsync
: After the component has been rendered to the DOM.
Refer to the Component Lifecycle documentation for more details.
Component Cascading Values
Cascading values allow you to pass data down through the component tree without explicitly passing it as parameters at each level. This is useful for themes, authentication status, or configuration.
For more in-depth information, explore the Hosting Models and Data Binding sections.