You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# Mud Blazor中向子组件传递父组件函数结果?

问题分析与解决

问题原因

你当前的写法存在两个核心问题:

  • 父组件传递的是方法本身(@parseString),而非方法执行后的字符串结果,子组件的text参数是string类型,类型不匹配导致最终text为null,渲染时触发空引用异常。
  • 子组件的text参数未设置默认值,当传入null时,@text渲染会引发空引用错误。

修正后的代码

父组件

需要调用parseString方法并传入具体参数,将返回的字符串传递给子组件:

<ChildComponent text="@parseString("需要处理的文本")"/>

@code{
    public string parseString(string text)
    {
        return text;
    }
}

子组件

给text参数设置默认值,避免空引用:

<MudText>@text</MudText>

@code{
    [Parameter]
    public string text { get; set; } = string.Empty;
}

额外说明

如果需要动态传递参数(比如绑定父组件的输入属性),可以这样写:

<!-- 父组件 -->
<input @bind="inputText" />
<ChildComponent text="@parseString(inputText)"/>

@code{
    private string inputText = "";
    public string parseString(string text)
    {
        // 可添加自定义处理逻辑,比如格式化文本
        return text?.ToUpper() ?? string.Empty;
    }
}

内容的提问来源于stack exchange,提问作者Erkam Bozan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:25:32