问题
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