在React serverside组件中设置<script>的内容

我有这个组件:

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> ) } } 

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

如果试试这个:

  getScript() { const config = JSON.stringify({ env: process.env.NODE_ENV }); return 'define(\"@config\", [], function () {' + ' return ' + config +';' + '});' } <head> <script>{this.getScript()} </script> </head> 

我在前面得到这个:

 <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> 

浏览器不能parsing这个,因为我得到: &quot; 字符而不是"'

不知道这是否会满足您的需求,但是您可以将脚本内容放在组件方法中,然后从jsx中调用方法

 export class Demo extends React.Component<DemoProps, any> { private foo: number; constructor(props: DemoProps) { super(props); } scriptContents(){ //contents of the script in here } render() { return ( <html> <head> <script> {this.scriptContents()} </script> </head> <body> <div id="root"> (hello world) </div> <div> <progress id="hot-reload-progress-bar" value="100" max="100"></progress> </div> </body> </html> ) } } 

最好的做法可能是使用React的天生的设施 – dangerouslySetInnerHTML的SetInnerHTML – 请看这个链接到React文档:

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

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

我得到这个function的唯一方法是:

 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> ) } }