在React服务器端组件中设置<script>的内容

Ale*_*lls 5 node.js reactjs server-side-rendering

我有这个组件:

export class Demo extends React.Component<DemoProps, any> {
    private foo: number;

    constructor(props: DemoProps) {
        super(props);
    }

    render() {
        return (
            <html>
            <head>

                <script>
                   // I would like to add an inline script here
                </script>

            </head>
            <body>
            <div id="root">
                (hello world)
            </div>
            <div>
                <progress id="hot-reload-progress-bar" value="100" max="100"></progress>
            </div>
            </body>
            </html>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在<script></script>标签内添加内联脚本?

如果尝试这个:

     getScript() {

        const config = JSON.stringify({
            env: process.env.NODE_ENV
        });

        return 'define(\"@config\", [], function () {' +
            ' return ' + config +';' +
            '});'
       }


       <head>
          <script>{this.getScript()} </script>
       </head>
Run Code Online (Sandbox Code Playgroud)

我在前端得到这个:

<html><head><script data-main="/js/main" src="/vendor/require.js"></script><script>define(&quot;@config&quot;, [], function () { return {&quot;env&quot;:&quot;local&quot;};}); </script></head><div><progress id="hot-reload-progress-bar" value="100" max="100"></progress></div><body><div id="root">Initial Home Page</div></body></html>
Run Code Online (Sandbox Code Playgroud)

浏览器无法解析它,因为我得到的是:&quot;字符而不是"or'

Ale*_*lls 3

最好的办法可能是使用 React 的固有功能 - dangerouslySetInnerHTML- 请参阅 React 文档的链接:

https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml

首先阅读文档!然后看看下面我的解决方案。

我让此功能发挥作用的唯一方法是使用以下内容:

export class Demo extends React.Component<DemoProps, any> {

    constructor(props: DemoProps) {
        super(props);
    }

    getScript() {   // return a string representing JS code

        const config = JSON.stringify({
            env: process.env.NODE_ENV
        });

         // return a plain JS object with the __html property
         // set to the string

        return {__html:'define("@config", [], function () {' +
            ' return ' + config +';' +
            '});'}
    }


    render() {

        return (
            <html>

            <head>
                <script dangerouslySetInnerHTML={this.getScript()}/>
            </head>

            <body>
            <div id="root">
            </div>

            </body>
            </html>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)