I've been trying to solve this for the past 5 hours, but couldn't find any solution - please help me solve this problem.
This is my code:
@foreach (string title in titleList)
{
<span> @title</span>
}
@code {
[Parameter]
public string theTitle { get; set; }
public static string[] titleList { get; set; } = theTitle.Split(", ");
}
I keep getting this error:
A field initializer cannot reference the non-static field, method, or property 'RelatedTopics.theTitle'
After I change to this:
[Parameter]
public static string theTitle { get; set; }
it still doesn't work in my application. Please help me with a solution for this.
CodePudding user response:
You can't use one instance variable to initialize another one using a field initializer. Instead put that code into OnParametersSet
lifecycle method.
@foreach (string title in titleList)
{
<span> @title</span>
}
@code{
[Parameter]
public string theTitle { get; set; }
private string[] titleList = Array.Empty<string>();
protected override void OnParametersSet()
{
if (!string.IsNullOrEmpty(theTitle))
{
titleList = theTitle.Split(", ");
}
}
}
If your string is space separated you should do theTitle.Split(" ");
instead of theTitle.Split(", ");