[Blazor] 모범사례 4. 올바른 매개변수

  • Blazor 네 번째 모범사례는 올바른 매개변수 사용방법 입니다.
  • Blaozr 를 개발을 진행하면 보통 컴포넌트 단위로 개발을 진행하고, 실제 부모가 되는 곳에 컴포넌트를 사용하여 부모 -> 자식 컴포넌트로 값들을 전달하는 형태로 개발합니다.
  • 때문에, Blazor 에서는 위 구조를 지키기 위해 Parameter 속성을 이용하여 매개변수 값들을 전달할 수 있습니다.
  • Blazor 에서 올바른 매개변수 사용하는 방법은 다음과 같습니다.

4.1 AKButton.razor 컴포넌트 생성

  • 우선 AKButton.razor 컴포넌트를 생성 후, 다음 코드를 작성합니다.
@namespace AKLab01.Blaozr.Components

<h3>AKButton</h3>

<button class="button primary" @attributes="UserAttributes">
    @Text
</button>
  • 위 컴포넌트는 단순히 button 태그에 class 속성과 @attributes 속성값 그리고 Button 안에 content 값으로 @Text 값을 추가하였습니다.

4.2 AKButton.razor.cs 속성 정의

  • 각 파라미터 속성 값들의 정의는 AKButton.razor.cs C# 프로젝트에 정의해 줍니다.
using Microsoft.AspNetCore.Components;

namespace AKLab01.Blaozr.Components;

public partial class AKButton
{
    [Parameter]
    public ButtonStyle ButtonStyle { get; set; } = ButtonStyle.Primary;

    [Parameter]
    public string? Text { get; set; }

    [Parameter]
    public bool IsFullWidth { get; set; }

    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> UserAttributes { get; set; } = new Dictionary<string, object>();

    [Parameter]
    public EventCallback OnClick { get; set; }

    [Parameter]
    public bool IsDisabled { get; set; }
}

public enum ButtonStyle
{
    Primary, Secondary, Outlined
}
  • 아직 위 모든 속성들을 사용하지는 않았지만, 컴포넌트에서 필요한 속성들은 프로젝트이름.razor.cs 파일에 [Parameter] 속성을 주고 선언해주면 됩니다.
  • 위와 같이 선언을 하게 되면, 밖에서 안으로 값을 주입받을 수 있게 됩니다.

4.3 부모에서 자식으로 값 전달

  • 마지막으로 AKButton.razor 컴포넌트를 부모 페이지에서 선언하고, 부모에서 값을 어떻게 전달하는지 확인합니다.
@page "/"
@using AKLab01.Blaozr.Components


<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<AKButton Text="First Primary Button"/>
  • 위와 같이 <AKButton Text="First Primary Button"/> Text 속성에 전달하고자 하는 문자열을 입력하여 전달하게 되면 해당 값이 자식 컴포넌트로 넘어와 바인딩 되는 것을 확인할 수 있습니다.

실행 결과

  • CSS 속성은 생략 했지만, 바인딩이 정상적으로 되어 Text 가 정상 출력 되는 것을 볼 수 있습니다.

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY