Adding script tag to React/JSX

后端 未结 17 1140
感动是毒
感动是毒 2020-11-22 03:52

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

\'use strict\';

import \'../../styles/         


        
17条回答
  •  庸人自扰
    2020-11-22 04:21

    This answer explains the why behind this behavior.

    Any approach to render the script tag doesn't work as expected:

    1. Using the script tag for external scripts
    2. Using dangerouslySetInnerHTML

    Why

    React DOM (the renderer for react on web) uses createElement calls to render JSX into DOM elements.

    createElement uses the innerHTML DOM API to finally add these to the DOM (see code in React source). innerHTML does not execute script tag added as a security consideration. And this is the reason why in turn rendering script tags in React doesn't work as expected.

    For how to use script tags in React check some other answers on this page.

提交回复
热议问题