터미널에서 새 Blazor 웹앱 생성
dotnet new blazor -o BlazorApp
새로 생성한 디렉토리로 이동
디렉토리 내 생성된 파일들
dotnet watch
Components/Pages/Home.razor 파일에 의해 정의된 페이지 출력
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
razor 파일 내에 작성된 내용으로 웹페이지에 출력
카운터에서 버튼 클릭 시 Current count가 증가함
Components/Pages/Counter.razor 파일 내에 작성된 내용으로 웹페이지 작동
@page "/counter"
@rendermode InteractiveServer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
원래 이런 거는 JavaScript로 써야하지만 Blazor에서는 C#으로 사용 가능
@rendermode 지시문에서 구성요소에 대해 대화형 서버 렌더링(=InteractiveServer)을 사용하도록 설정함
<aside> ⛺ ASP.NET Core Blazor 렌더링 모드
각 .razor 파일은 재사용 가능한 UI 구성 요소를 정의한다
Home.razor 파일 수정
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<Counter />
<Counter /> 를 추가해서 Counter 구성 요소가 Home에 표시되도록 변경함
구성 요소 매개 변수는 특성 또는 자식 컨텐츠를 사용하여 지정되며, 이를 통해 하위 구성 요소에 대한 속성을 설정할 수 있다
Counter 구성 요소에 매개 변수를 정의해서 버튼 클릭 시마다 증가하는 양 지정하기
@page "/counter"
@rendermode InteractiveServer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
[Parameter]
public int IncrementAmount {get; set;} = 1;
private void IncrementCount()
{
currentCount += IncrementAmount;
}
}
[Parameter] 특성을 사용해서 IncrementAmount 라는 공개 속성 추가
기본값 1 로 지정
IncrementCount 함수가 호출될 때 currentCount가 IncrementAmount 만큼씩 증가하게 수정