将 React 与 Nashorn 一起使用会抛出“ReferenceError: 'console' is not d

Using React with Nashorn throws "ReferenceError: "console" is not defined"

本文关键字:ReferenceError console not is Nashorn React 一起      更新时间:2023-09-26

我正在使用"react": "~0.12.2"

和以下代码:

@RequestMapping("/")
@ResponseBody
private String home() throws ScriptException, IOException {
    loadReact();
    InputStream jsStream = resourceLoader.getResource("classpath:public/js/server.js").getInputStream();
    engine.eval(new InputStreamReader(jsStream));
    return engine.eval("renderServerside()").toString();
}
private void loadReact() throws ScriptException, IOException {
    InputStream jsStream = resourceLoader.getResource("classpath:public/lib/react/react.js").getInputStream();
    // React expects 'window' or 'global' to be set
    engine.eval("var global = this");
    engine.eval(new InputStreamReader(jsStream));
}

我的服务器.js如下所示:

function renderServerside() {
    var MyComponent = React.createClass({
        render: function () {
            return React.DOM.h1(null, 'Hi, ' + this.props.msg)
        }
    });
    return React.renderComponentToString(MyComponent({msg: 'World!'}));
}

并得到这个异常:

javax.script.ScriptException: ReferenceError: "console" is not defined in <eval> at line number 18108] with root cause
jdk.nashorn.internal.runtime.ECMAException: ReferenceError: "console" is not defined

那么纳斯霍恩怎么能不提供控制台呢?

我厌倦了实现此页面中的基本示例:与 Nashorn 一起反应

Rhino之前也没有提供。您可以使用类似的东西实现自己的控制台

console = { 
    log: print,
    warn: print,
    error: print
};

要获得完整的控制台支持,您可能需要添加更多功能。请参阅:控制台