Adding script tag to React/JSX

后端 未结 17 928
感动是毒
感动是毒 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

    There is a very nice workaround using Range.createContextualFragment.

    /**
     * Like React's dangerouslySetInnerHTML, but also with JS evaluation.
     * Usage:
     *   
    */ function setDangerousHtml(html, el) { if(el === null) return; const range = document.createRange(); range.selectNodeContents(el); range.deleteContents(); el.appendChild(range.createContextualFragment(html)); }

    This works for arbitrary HTML and also retains context information such as document.currentScript.

提交回复
热议问题