Adding script tag to React/JSX

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

    According to Alex McMillan's solution, I have the following adaptation.
    My own environment: React 16.8+, next v9+

    // add a custom component named Script
    // hooks/Script.js

    import { useEffect } from 'react'
    
    const useScript = (url, async) => {
      useEffect(() => {
        const script = document.createElement('script')
    
        script.src = url
        script.async = (typeof async === 'undefined' ? true : async )
    
        document.body.appendChild(script)
    
        return () => {
          document.body.removeChild(script)
        }
      }, [url])
    }
    
    export default function Script({ src, async=true}) {
    
      useScript(src, async)
    
      return null  // Return null is necessary for the moment.
    }
    

    // Use the custom compoennt, just import it and substitute the old lower case */} {/* new custom Script component */}

提交回复
热议问题