简体   繁体   中英

Blazor Invoking null

I have a small but interesting problem which I can't wrap my head around. I have a custom DatePicker component which uses TValue as Value (generic, you can pass DateTime or DateTime? as TValue). And inside a calendar I have button 'x' which clears the Value to default of TValue

    [Parameter]
    public EventCallback<TValue> ValueChanged { get; set; }
    
    protected async void ClearInputData()
    {
        await ValueChanged.InvokeAsync(default(TValue));
        Value = default(TValue);
        selectedHour = 0;
        selectedMinute = 0;
        selectedSecond = 0;
        OnInput?.Invoke();
    }

The problem is that default(TValue) if TValue == DateTime is null, and you cannot invoke null; What could be the smartest way ot getting around this?

I tried to reproduce your problem.

My DateComponent:

    <h3>DateComponent</h3>
    
    @typeparam TValue
    <p>Value: @Value</p>
    <button @onclick="() => ClearInputData()">X</button>
    
    @code {
        [Parameter]
        public EventCallback<TValue> ValueChanged { get; set; }
    
        [Parameter]
        public TValue Value { get; set; }
    
        protected async Task ClearInputData()
        {
            await ValueChanged.InvokeAsync(default(TValue));
            Value = default(TValue);
        }
    }

My consumer:

    <DateComponent TValue="DateTime?" @bind-Value="@Value1"></DateComponent>
    <p>@(Value1.HasValue ? Value1 : "(null)")</p>
    
    <DateComponent TValue="DateTime" @bind-Value="@Value2"></DateComponent>
    <p>@Value2</p>
    
    @code {
        DateTime? Value1 { get; set; } = DateTime.Now;
        DateTime Value2 { get; set; } = DateTime.Now;
    }

In my example, everything works as expected. Did I miss something?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM