我正在尝试将我的简单应用程序组件化,并且当一切都在一个组件中时,这一切都有效。但是,当我将按钮逻辑移到它自己的子组件中并移出主组件时,我得到以下信息
Unable to set property 'story' on object of type 'Shared.ChoiceButton'. The error was: Specified cast is not valid. ---> System.InvalidCastException: Specified cast is not valid
我可以看到这是一个转换错误,但是当我尝试使用原语做同样的事情时,它可以工作。我缺少什么技巧才能使它与复杂类型一起使用?
父组件
<div id="choices">
@foreach (var choice in story?.currentChoices)
{
<ChoiceButton story="@story" choice="@choice" />
}
</div>
@code {
public Story story;
protected override async Task OnInitializedAsync()
{
story = new Story(await Http.GetStringAsync("sample-data/Deamons.json"));
}
}
我的新子组件(ChoiceButton)
<button class="choiceButton" @onclick="() => Choose(choice)">@choice.text</button>
@code {
[Parameter] public Story story { get; set; }
[Parameter] public Choice choice { get; set; }
void Choose(Choice choice)
{
story.ChooseChoiceIndex(choice.index);
story.ContinueMaximally();
}
}