gpt4 book ai didi

blazor - 每当父组件更新时,我们如何渲染子组件?

转载 作者:行者123 更新时间:2023-12-04 09:38:07 25 4
gpt4 key购买 nike

子组件根据对象的一组属性构造一个字段,该字段作为参数传递给子组件。在下面的示例中,当父组件中的任何地址字段发生变化时,子组件如何动态呈现?感谢您的任何建议!

父组件使用如下子组件并传递参数 parentObj .

父组件:

<Child ChildObj="@parentObj" />

子组件:
<div class="col-8 flex-wrap">
@Address
</div>

@code {

[Parameter]
public Person ChildObj { get; set; }

public string Address { get; set; }


protected override async Task OnInitializedAsync()
{
await Task.Run(() => {
if (ChildObj != null)
{
Address = ChildObj.Address1 + " " + ChildObj.Address2 + " " + ChildObj.City + " " + ChildObj.State + " " + ChildObj.Zip
}
});

}
}

最佳答案

这里的问题是 OnInitializedAsync仅在组件中第一次设置参数时调用,需要使用OnParametersSet将在以下情况下调用:

OnParametersSetAsync or OnParametersSet are called:

  • After the component is initialized in OnInitializedAsync or OnInitialized.
  • When the parent component re-renders and supplies: Only known primitive immutable types of which at least one parameter has changed. Any complex-typed parameters. The framework can't know whether the values of a complex-typed parameter have mutated internally, so it treats the parameter set as changed.

<div class="col-8 flex-wrap">
@Address
</div>

@code {

[Parameter]
public Person ChildObj { get; set; }

public string Address { get; set; }

// using OnParametersSet
protected override void OnParametersSet()
{
if (ChildObj != null)
{
Address = ChildObj.Address1 + " " + ChildObj.Address2 + " " + ChildObj.City + " " + ChildObj.State + " " + ChildObj.Zip
}
}
}

关于blazor - 每当父组件更新时,我们如何渲染子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62457521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com