gpt4 book ai didi

c# - 可以在 Blazor 中将 ElementRef 属性设置为 javascript 互操作返回值吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:44 25 4
gpt4 key购买 nike

我正在修改文本区域元素上的 CodeMirror。我正在使用 javascript interop 来完成此操作,并且在应用代码镜像时它工作正常。然而,我的意图是返回该 codemirror 元素并将其存储在另一个 elementref 中。

Blazor.registerFunction('BlazorExt.CodeMirrorSetupExt', (element) =>
{
return CodeMirror.fromTextArea(element,
{
mode: 'application/ld+json',
matchBrackets: true,
autoCloseBrackets: true,
indentWithTabs: true,
lineNumbers: true,
autofocus: true,
styleActiveLine: true,
readOnly: false,
autoCloseBrackets: true,
foldGutter: true,
height: 'auto',
width: 'auto',
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
});
});

public static ElementRef CodeMirrorSetupExt(this ElementRef elementRef)
{
var result = RegisteredFunction.Invoke<ElementRef>("BlazorExt.CodeMirrorSetupExt", elementRef);
return result;
}

在我的组件中:

//in my html i have a textarea with ref of TextArea

ElementRef CodeMirror;
ElementRef TextArea;

protected override void OnAfterRender()
{

CodeMirror = TextArea.CodeMirrorSetupExt();
}

理想情况下,在这一点之后,我应该能够像这样使用它的功能来更新我的 codemirror ref。

    Blazor.registerFunction('BlazorExt.CodeMirrorUpdateExt', (element, Value) =>
{
element.getDoc().setValue(Value);
});

public static void CodeMirrorUpdateExt(this ElementRef elementRef, string Value)
{
var args = new object[] { elementRef, Value };
RegisteredFunction.Invoke<object>("BlazorExt.CodeMirrorUpdateExt", args);
}

再次在组件中,我应该能够像这样更新代码镜像:

CodeMirror.CodeMirrorUpdateExt("somedata");

但是我得到一个异常:Microsoft.AspNetCore.Blazor.Browser.Interop.JavaScriptException: Cannot read property 'getDoc' of null

我想要完成的事情是可能的还是将 codemirror javascript 对象传递到 elementref 是不可能的?

最佳答案

我扩展了@Flores 的回答。无需创建所有 javascript 对象的全局数组,只需将新值存储在您已有 elementReference 的 javascript DOM 对象中。

window.hintCodeMirrorIntegration = {
initialize: function(element, markupMode) {
element.codeMirrorLink = CodeMirror.fromTextArea(element,
{
...
});
return 0;
},

getCode: function(element) {
return element.codeMirrorLink.getValue();
}

}

在 C# 端,我将 ElementReference 传递给文本区域。我保留该引用,当我需要 CodeMirror 对象的代码时,我在我已经引用的 TextArea 中找到它。这也很好地将 CodeMirror 对象的生命周期与其正在隐藏的文本区域联系起来。

 private ElementReference textToEdit;
protected override Task OnAfterRenderAsync()
{
return javascriptRuntime.InvokeAsync<int>("hintCodeMirrorIntegration.initialize", textToEdit,
Context.CurrentAsset.MimeType);
}

private async Task Save()
{
var code = await javascriptRuntime.InvokeAsync<string>("hintCodeMirrorIntegration.getCode", textToEdit);
//... save the result in the database
}

关于c# - 可以在 Blazor 中将 ElementRef 属性设置为 javascript 互操作返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com