在 blazor 中改变组件属性的正确方法

Gui*_*rme 9 c# razor asp.net-core blazor

我有两个组件,Child.razorParent.razor.

Child.razorHTML:

<input type="text" value="@Text" />
Run Code Online (Sandbox Code Playgroud)

Child.razorC#:

[Parameter] public string Text { get; set; }
Run Code Online (Sandbox Code Playgroud)

Parent.razorHTML:

<Child @ref="child_1" />
<Child @ref="child_2" />
<Child @ref="child_3" />
Run Code Online (Sandbox Code Playgroud)

Parent.razor C#:

Child child_1;
Child child_2;
Child child_3;

void SetText(Child item, string text)
{
    item.Text = text;
}
Run Code Online (Sandbox Code Playgroud)

我收到警告item.Text = text

警告 BL0005:不应在其组件之外设置组件参数“文本”。

经过一番谷歌搜索,我发现了这个问题:BL0005 - 外部参数使用 - 为什么会出现警告?

答案很好,但它没有提供替代方案(github 上的链接内容也不是很有帮助)。

从父级改变组件参数的正确方法是什么?

编辑

再澄清一点:我知道我可以使用绑定,但我需要能够更改SetText方法内的值,将我想要变异的 Child 作为参数传递。绑定的问题在于变量没有与组件绑定。换句话说:对于 Child 的引用,我不知道应该设置哪个绑定字符串。

例如:

<Child @ref="child_1" @Text="binding_1" />
<Child @ref="child_2" @Text="binding_2"/>
<Child @ref="child_3" @Text="binding_3"/>
Run Code Online (Sandbox Code Playgroud)

Parent.razor C#:

Child child_1;
Child child_2;
Child child_3;

string binding_1;
string binding_2;
string binding_3;

void SetText(Child item, string text)
{
     // which binding string should I set?
}
Run Code Online (Sandbox Code Playgroud)

我可以想象一些时髦的代码,创建一个Dictionary<Child, string>将组件与绑定字符串相关联的东西,或者类似的东西,但是......真的吗?

Isa*_*aac 4

您可以在父组件中定义Child类型的属性,并将父组件 (this) 的引用传递给 Parent 类型的子组件属性。现在,子组件保存了对父组件的引用,并且它可以将自身(再次使用此组件)添加到父组件中。现在您有了对子组件的引用,并且可以将其 Text 属性设置为有趣的内容。我希望我很清楚,如果没有,我会发布代码来反映这一点。以下代码有效...

儿童剃须刀

<input type="text" value="@Text" />

@code
{
    [Parameter] public string Text { get; set; }
    public void SetText(string text)
    {
        Text = text;
        StateHasChanged();
    }
    [ParameterAttribute] public Parent Parent { get; set; }
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            Parent.AddToParent(this);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在父组件 ( Text="Some Text") 中分配的原始组件参数 Text 的值在文本框中不可见,因为在 Parent 的 SetText 方法调用 Child 的 SetText 方法之后,该方法又将传递给它的值分配给 Text 属性,并且因此在文本框中看到的值是“新文本”

父母剃刀

<Child Parent="this" Text="Some Text" />

@code{
    public void AddToParent(Child child)
    {
        string text = "new text";
        SetText(child, text);
    }

    void SetText(Child item, string text)
    {
        // which binding string should I set?
        item.SetText(text);

    }
}
Run Code Online (Sandbox Code Playgroud)

用法

<Parent />
Run Code Online (Sandbox Code Playgroud)

  • 史蒂夫·桑德森;-) (2认同)