ReactDOMServer-如何使用renderToString方法忽略某些值的转堆

时间:2019-07-05 06:46:18

标签: reactjs ssr react-dom

有时候,我想忽略renderToString中的转堆。

我正在使用React作为模板引擎来生成模板的基础(html,标头,正文)。我需要注入一个值(将json对象作为字符串,用JSON.stringify转换),以便可以在浏览器中将其作为全局变量进行访问。

这是我的模板组件:

export default function (props) {
    return (
        <html>
            <head>
                <meta charSet="utf-8"/>
            </head>
            <body className="rtl">
                <div id="app-root"></div>
                <script>
                    myValue = {JSON.stringify(props.obj)}
                </script>
            </body>
        </html>
    );
}

这是渲染和传递值的地方:

let template = <Template obj={obj}/>;

template = ReactDOMServer.renderToString(template);

template = '<!DOCTYPE html>' + template;

res.status(status).send(template);

运行此命令后,“ myValue”未定义,因为renderToString将insert插入为HTML注释,并更改数据结构(转换字符),如下所示:

<script>
myValue = <!-- -->{&quot;a&quot;:&quot;a&quot;,&quot;b&quot;:&quot;b&quot;}
</script>

如何解决?

1 个答案:

答案 0 :(得分:1)

尝试此https://zhenyong.github.io/react/tips/dangerously-set-inner-html.html。 像这样:

<script dangerouslySetInnerHTML={JSON.stringify(props.obj)} />