C# Blazor study notes (1): Blazor basic syntax, componentization and life cycle

foreword

Here we will explain the basic syntax and simple componentization of Blazor

Blazor Common Syntax Introduction

basic grammar

routing

@Page

routing location

@page "/fetchdata"

Conditional Generation of Page Elements

@if / else

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
    </table>
}

@for

@for(var i = 0;i< 10; i++)
{
    <text>我是text @i</text>
}

@foreach

@foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }

to bind

parameter binding (assignment, one-way)

<input title="@Title" value="@Value"  />

@code {

    [Parameter]
    public string Title{ get; set; }

    [Parameter]
    public string Value { get; set; }



}

Parameter binding (two-way)

<input @bind="Title" />

@code {
    public string Title{ get; set; }
}

event binding

<button @onclick="ShowTest"/>

@code {
    public void ShowTest()
    {
        Console.WriteLine("我被按钮点击了");
    }
}

Dictionary binding @attributes

Simplify property binding for controls


<input @attributes="InputList" />
//等价于 <input title="我的标题" value = "10" />
@code {
    
    

    public Dictionary<string, object> InputList {
    
     get; set; } = new Dictionary<string, object>()
    {
    
    
        {
    
    "title","我的标题"},
        {
    
    "value","10"}
    };
}


Componentization

  • Only razor can be componentized
  • The first letter of the razor file name must be capitalized
  • No injection is required, components can be used directly. So in order to avoid file name conflicts, it is necessary to standardize the naming

how to use

insert image description here

@Parameter parameter injection

Parameter injection supports multiple parameters

  • common data type
  • List type
  • Action delegation
@code {
    
    

    [Parameter]
    public string Title{
    
     get; set; }

    [Parameter]
    public string Value {
    
     get; set; }



    [Parameter]
    public List<string> TestList {
    
     get; set; } = new List<string>();


}

use

<Test Title="我是测试的标题" Value="数值" TestList="@strList"/>

@code{
    
    
    public List<string> strList = new List<string>()
    {
    
    

    };

    protected override Task OnInitializedAsync()
    {
    
    
        for(var i = 0;i < 10; i++)
        {
    
    
            strList.Add("我是标题" + i);
        }
        return base.OnInitializedAsync();
    }


}

Callback

Component declaration callback

Inside Test.Razor

    [Parameter]
    public EventCallback<string> OnClick{
    
     get; set; }
    //string是回调的返回参数

Component injection callback

reference component


<Test  OnClick="TestBtn"/>

@code{
    
    


	//注意,注入的函数的参数和回调的参数要保持一致
    public void TestBtn(string msg)
    {
    
    
        Console.WriteLine("我接收到了回调"+msg);
    }

}

Component fires callback

Test.razor


<button @onclick="ShowTest"/>
@code {
    
    



    [Parameter]
    public EventCallback<string> OnClick{
    
     get; set; }

	//通过按钮事件触发回调,这样引用的页面就会触发回调函数
    public void ShowTest()
    {
    
    
        OnClick.InvokeAsync("点击回调函数");
    }

}

direct control @ref

Use @ref to directly control component elements

Test is the component we defined

//通过@ref直接使用组件
<Test @ref="myTest"  OnClick="TestBtn"/>

@code{
    
    
	//先声明组件
    private Test myTest {
    
     get; set; }

	//通过某种方式调用组件,我这里是用按钮点击
    public void TestBtn(string msg)
    {
    
    
        myTest.Title = "我直接操控修改了Title";
        myTest.TestBtn();
        Console.WriteLine("我接收到了回调"+msg);
    }

}

life cycle

App initial stage:

In this phase, the Blazor application initializes and loads the required resources.

  • OnInitializeAsync:
    • Called when the application is initialized, usually to perform some initialization operations.
      Component rendering phase: In this phase, components will be rendered and presented into the user interface.
  • OnParametersSet:
    • Called after the component receives a new parameter value, you can perform parameter-related operations in this method.
      OnAfterRender: Called after the component is rendered to the screen, operations related to DOM operations can be performed in this method.

Lifecycle hook phase:

At this stage, Blazor provides some specific lifecycle hook methods that can be used to perform some specific operations.

  • OnInitialized:
    • Called after the component initialization is complete, you can perform some initialization logic in this method.
  • OnAfterRenderAsync:
    • Called after the component is rendered to the screen, you can perform asynchronous operations in this method.
  • OnParametersSetAsync:
    • Called after the component receives new parameter values, you can perform asynchronous operations in this method.

App termination phase:

At this stage, the Blazor application will finish and clean up.

  • We dispose:
    • Invoked when the component is removed from the DOM, some cleanup logic can be performed in this method.

debugging

hot reset

insert image description here

console output

Because C# is used instead of JS. So the console.log method of JS cannot be used directly. But you can use C#'s Console.WriteLine()

Printed in the running console

insert image description here

Guess you like

Origin blog.csdn.net/qq_44695769/article/details/132021920