当子组件更改父组件值时,Blazor运行自定义事件

时间:2020-03-07 21:55:10

标签: blazor blazor-server-side

我有一个父子组件:

父组件

<IncrementButton Increment="-1" @bind-Attribute="Amount" @onclick="@(() => UpdateBottomPillText())" />
<span>@Amount</span>
<IncrementButton Increment="1" @bind-Attribute="Amount" @onclick="@(() => UpdateBottomPillText())" />
<span>@bottomPillAmount</span>

@code {
    [Parameter] public int Amount { get; set; }
    [Parameter] public EventCallback<int> AmountChanged { get; set; }

    string bottomPillAmount;

    string UpdateBottomPillText()
    {
        double amountAdded = Math.Floor(((double)(Amount - 10.0)) / 2.0);

        bottomPillAmount = amountAdded > 0 ? "+" + amountAdded.ToString() : amountAdded.ToString();

        return Amount.ToString();
    }

    protected override void OnParametersSet()
    {
        UpdateBottomPillText();
    }

}

子组件(IncrementButton

<button type="button" @onclick="OnAttributeChanged">@displayText</button>

@code {
    [Parameter]
    public int Increment { get; set; } = 1;

    [Parameter]
    public int Attribute { get; set; }

    [Parameter]
    public EventCallback<int> AttributeChanged { get; set; }

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

    string displayText;

    protected override void OnParametersSet()
    {
        displayText = Increment > 0 ? "+" + Increment.ToString() : Increment.ToString();
    }

    private Task OnAttributeChanged()
    {
        Attribute += Increment;
        await OnClick.InvokeAsync(new MouseEventArgs());
        return AttributeChanged.InvokeAsync(Attribute);
    }
}

按下@bind-Attribute="Amount"IncrementButton会工作并更新值,但是我想运行UpdateBottomPillText()以及更新值。现在,我正在通过onclick事件进行操作,但是有没有办法在父组件中修改AttributeChanged事件?

1 个答案:

答案 0 :(得分:1)

这里您需要适当地设置组件之间的双向数据绑定。

IncrementButton.razor

Virtual machine Scale set

用法

<button type="button" @onclick="OnAttributeChanged">@displayText</button>

@code {
[Parameter]
public int Increment { get; set; } = 1;

[Parameter]
public int Attribute { get; set; }

[Parameter]
public EventCallback<int> AttributeChanged { get; set; }


string displayText;

protected override void OnParametersSet()
{
    displayText = Increment > 0 ? "+" + Increment.ToString() : 
                                                Increment.ToString();
}

private Task OnAttributeChanged()
{
    Attribute += Increment;
    return AttributeChanged.InvokeAsync(Attribute);
}
}