在我的组件中,我有一个子组件(FooComponent
(,在那里我向它传递一个参数,并获得一个参考
家长剃刀
<FooComponent @ref="FooComponentRef" FooParameter="@MyValue"/>
<button @onclick="Test">@MyValue</button>
@code {
FooComponent FooComponentRef { get; set; }
string MyValue { get; set; }
int count { get; set; }
void Test(){
MyValue = "SomeValue" + count++;
FooComponentRef.FooFunction();
}
}
我修改了代码,使其成为一个简单且可测试的示例
我有一个函数(Test
(,它将更新参数中传递的属性(传递给FooParameter
的MyValue
(,并从ref(FooComponent
的FooFunction
(调用一个函数。
在FooComponent
内部
FooComponent.rarzor
<div>
<div>FooParameter: @FooParameter</div>
<div>ValueUsedInFooFunction: @ValueUsedInFooFunction</div>
</div>
@code {
[Parameter]
public string FooParameter { get; set; }
public string ValueUsedInFooFunction { get; set; }
public void FooFunction()
{
// This function is using FooParameter to make some logic
ValueUsedInFooFunction = FooParameter;
}
}
我修改了代码,使其成为一个简单且可测试的示例
它使用FooFunction
中的FooParameter
来做一些逻辑。
问题是,当我更改MyValue
并调用FooFunction
时,组件还没有更新,所以它使用";旧的";FooParameter
的值,但我需要使用新设置的值,即正确的MyValue
。
另一个很难解决的问题是,我无法更改FooFunction
(它不是我创建的函数(。
我已经尝试过使用所有东西(StateHasChanged
、InvokeAsync
(,但仍然没有解决方案。
我需要的是我的Test
函数来做一些类似的事情
void Test(){
MyValue = "SomeValue" + count++;
// Somehow update UI so FooParameter have the correct value of MyValue
FooComponentRef.FooFunction();
}
这是测试的小提琴
在小提琴中,当点击按钮并调用Test
函数时,您会看到ValueUsedInFooFunction
始终是";旧的";FooParameter
的值,意味着FooFunction
在FooParameter
被更新之前被执行。
此更改将使起作用
void Test(){
MyValue = "SomeValue" + count++;
FooComponentRef.FooParameter = MyValue;
FooComponentRef.FooFunction();
}
您将不传递字符串参数(MyValue(,而是传递一个对象Dto,该对象具有一个包含该值的字符串属性。这是Dto:
public class FooDto
{
public string MyValue { get; set; }
}
这是索引:
@page "/"
@using WebApplication2.Models
<FooComponent @ref="FooComponentRef" FooDtoParameter="@_dto" />
<button @onclick="Test">@MyValue</button>
@code {
FooComponent FooComponentRef { get; set; }
string MyValue { get; set; }
int count { get; set; }
/// <inheritdoc />
protected override void OnInitialized()
{
base.OnInitialized();
// The Dto class will be passed as a parameter to foo.
_dto = new FooDto();
}
void Test()
{
_dto.MyValue = "SomeValue" + count++;
FooComponentRef.FooFunction();
}
private FooDto _dto;
}
Foo:
@using WebApplication2.Models
<div>
<div>FooParameter: @FooDtoParameter.MyValue</div>
<div>ValueUsedInFooFunction: @ValueUsedInFooFunction</div>
</div>
@code {
[Parameter]
public FooDto FooDtoParameter { get; set; }
public string ValueUsedInFooFunction { get; set; }
public void FooFunction()
{
// This function is using FooParameter to make some logic
ValueUsedInFooFunction = FooDtoParameter.MyValue;
}
}
子组件和父组件使用相同的Dto对象进行通信,当您更改特性的值时,子组件可以立即访问该信息。
我知道可能有更好的方法可以做到这一点,但我正在努力回答这个具体案例的问题。