【问题标题】:Blazor set value inside other componentBlazor 在其他组件内设置值
【发布时间】:2024-04-10 14:45:01
【问题描述】:

我正在构建我的页面,我想知道是否可以让我的生活更轻松,并在方法中放置一些简单的自定义输入框,然后它们会将我的值的引用传递给它们

<div class="col-12 row">
    <label class="col-2">@Caption</label>
    <InputNumber class="form-control col-3" @bind-Value="@Value"/>
</div>
<br />

@code {
    [Parameter]
    public string Caption { get; set; }
    
    [Parameter]
    public int Value { get; set; }
}

然后像这样使用它

<CustomInputNumber Caption="Price" Value="@Product.Price" />

可以这样设置值吗?或者传递对象作为参考?感谢您的帮助!

【问题讨论】:

    标签: c# asp.net-core web-applications components blazor


    【解决方案1】:

    我要解决的方法是从 inputbase 继承并基本上构建您自己的输入。 Chrissainty 有一篇很棒的博客文章,我认为这比我引用他在该文章中已经解释的一半内容要清楚得多。

    https://chrissainty.com/building-custom-input-components-for-blazor-using-inputbase/

    如果你真的想包装已经存在的输入组件,你可以这样做:

    组件

    <div class="col-12 row">
        <label class="col-2">@Caption</label>
        <InputNumber class="form-control col-3" Value="Value" TValue="int" ValueChanged="HandleValueChanged" ValueExpression="(()=>Value)"  />
    </div>
    <br />
    
    @code{
        [Parameter]
        public string Caption { get; set; }
    
        [Parameter]
        public int Value { get; set; }
    
        [Parameter]
        public EventCallback<int> ValueChanged { get; set; }
    
        public void HandleValueChanged(int newValue)
        {
            ValueChanged.InvokeAsync(newValue);
        }
    }
    

    用法如下:

    <ExampleComponent @bind-Value="ExampleValue"/>
    

    在这里,您基本上覆盖了默认输入字段中存在的现有事件。当默认组件注意到更改时,您调用自己的 valuechanged 事件将事件传递给它的父级。

    尽管如此,我认为第一个解决方案更清洁。

    【讨论】:

    • 这比我预期的要好得多,非常感谢
    • InputNumber 组件必须嵌套在 EditForm 组件中。它不能单独存在。上述解决方案不考虑它。注意 Value 参数不应该被组件改变:github.com/dotnet/aspnetcore/issues/…
    • 这是真的@enet。但由于所有标准输入组件都是如此,为简洁起见,我没有包括它。不知道关于更改 Value 参数,所以我会快速编辑它!