【问题标题】:Blazor JS interop: how to pass undefined to a JavaScript functionBlazor JS 互操作:如何将 undefined 传递给 JavaScript 函数
【发布时间】:2021-01-13 02:20:21
【问题描述】:

在 blazor 项目中,JavaScript 函数区分 nullundefined。当从 C# (await jsRuntime.InvokeAsync<long>("func", null, "str")) 传递 null 时,JS 端接收值 null (typeof arg1 === 'object')。从 C# 端传递什么来接收undefined (typeof arg1 === 'undefined')?

编辑: 显然null 的行为并不一致,这取决于参数的位置。 JS:

        func1: function (arg1) {
            console.log("func1", typeof arg1);
        },
        func2: function (arg1, arg2) {
            console.log("func2", typeof arg1);
        },

C#:

        await jsRuntime.InvokeVoidAsync("utils.func1", null);
        await jsRuntime.InvokeVoidAsync("utils.func1");
        await jsRuntime.InvokeVoidAsync("utils.func1", "aaa");
        await jsRuntime.InvokeVoidAsync("utils.func2", null, 123);
        await jsRuntime.InvokeVoidAsync("utils.func2", "aaa", 123);

输出:

func1 undefined
func1 undefined
func1 string
func2 object
func2 string

【问题讨论】:

  • 你试过await jsRuntime.InvokeAsync<long>("func")吗?
  • 无复制。你可以发布 JS func() 吗?并告诉我们您使用的是什么版本。
  • 已编辑:添加了一个重现问题的示例。当然,可以省略最后的参数以在 JS 中获取 undefined。我的问题是中间论点未定义。

标签: javascript blazor blazor-webassembly


【解决方案1】:

如果您想知道您是否发送参数或 JavaScript 函数中是否为 null,您可以使用 ===undefined===null

<script>
    var func1=(arg1)=> {
        console.log("func1", arg1,arg1===null,arg1===undefined,typeof arg1);
    }
</script>

但你需要发送“null explicity”

    var data = (string)null; //<--I check with this
    await JSRuntime.InvokeAsync<string>("func1","Hello world");
    await JSRuntime.InvokeAsync<string>("func1", data);
    await JSRuntime.InvokeAsync<string>("func1");

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多