如何在 React.NET 中导出 JavaScript 文字
How can I export a JavaScript literal in React.NET
我正在使用属性来传递组件依赖项。这在进行服务器端渲染时尤为重要,代码依赖于 运行-time 库,如 jQuery 或 SignalR。在我的例子中,我需要在服务器端呈现我的组件,然后让 JS 连接到它并在浏览器中流式传输实时数据。所以我不需要 SignalR 服务器端,但我需要使用 React.NET.
传递对客户端上的网络套接字集线器的引用
@Html.React("Comments", new
{
data = Model,
conn = "$.hubConnection()" //<--- I need this to be a literal not a string
})
在深入研究 React.NET 的源代码后,我发现它使用 Newtonsoft
来序列化数据。所以你可以使用 JRaw
.
@Html.React("Comments", new
{
data = Model,
conn = new Newtonsoft.Json.Linq.JRaw("$.hubConnection()")
})
然后我只需要包含一个简单的模拟,这样它就不会在服务器端渲染期间抛出错误。
// this file contains mocks for global variables that are referenced by server-side code but only needed client-side. For example SignalR.
// mock jQuery
var $ = jQuery = {};
// mock SignalR API
$.hubConnection = function() {};
很有魅力!
我正在使用属性来传递组件依赖项。这在进行服务器端渲染时尤为重要,代码依赖于 运行-time 库,如 jQuery 或 SignalR。在我的例子中,我需要在服务器端呈现我的组件,然后让 JS 连接到它并在浏览器中流式传输实时数据。所以我不需要 SignalR 服务器端,但我需要使用 React.NET.
传递对客户端上的网络套接字集线器的引用@Html.React("Comments", new
{
data = Model,
conn = "$.hubConnection()" //<--- I need this to be a literal not a string
})
在深入研究 React.NET 的源代码后,我发现它使用 Newtonsoft
来序列化数据。所以你可以使用 JRaw
.
@Html.React("Comments", new
{
data = Model,
conn = new Newtonsoft.Json.Linq.JRaw("$.hubConnection()")
})
然后我只需要包含一个简单的模拟,这样它就不会在服务器端渲染期间抛出错误。
// this file contains mocks for global variables that are referenced by server-side code but only needed client-side. For example SignalR.
// mock jQuery
var $ = jQuery = {};
// mock SignalR API
$.hubConnection = function() {};
很有魅力!