How do I use Embed Code in React with Hooks

拜拜、爱过 提交于 2020-04-18 06:31:33

问题


I have the following embed code I need to integrate into my React app (using hooks):

<script 
class="123abc" 
type="text/javascript" 
src="https://cdn2.fake.com/Scripts/embed-button.min.js" 
data-encoded="lsakjdfioejfklsdKLJFLDSidjfklJSDJfLFKJEI88DdfDF8Ad9sa7">
</script>

How would I go about doing this? The resources I've found don't seem to allow me to implement the data-encoded part...

Based on Adding script tag to React/JSX you can see the answer has a useEffect & hooks solution, but I can't figure out how I would implement the data-encoded part (or the class part for that matter).


回答1:


you can create a portal to add a script block instead of mutating the DOM directly from within your react script!




回答2:


For editing the documents head usually you use react-helmet.

Supports all valid head tags: title, base, meta, link, script, noscript, and style tags.




回答3:


How about this:

componentDidMount () {
    const script = document.createElement("script");
    script.src = "https://cdn2.fake.com/Scripts/embed-button.min.js";
    script.async = true;

    document.body.appendChild(script);
}


来源:https://stackoverflow.com/questions/60918188/how-do-i-use-embed-code-in-react-with-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!