简体   繁体   中英

ReactDOMServer - how to ignore trans-pile some values with renderToString method

sometime, i want ignore trans-pile in renderToString.

i'm using React as template engine to generate base of template (html, header, body). i need to inject a value (a json object as string,converted with JSON.stringify) to can access to it as global variable on the browser.

this is my Template component:

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

this is render and pass value place:

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

template = ReactDOMServer.renderToString(template);

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

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

after running this, 'myValue' is undefined because renderToString insert insert as HTML comment and also change structure of data (convert characters) like this:

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

how to fix it?

Try this https://zhenyong.github.io/react/tips/dangerously-set-inner-html.html . Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM