V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
blue7wings
V2EX  ›  React

React 如何使用外部 JS 文件(CDN 文件),并使用其中的对象?

  •  
  •   blue7wings · 2022-09-08 17:06:58 +08:00 · 1721 次点击
    这是一个创建于 567 天前的主题,其中的信息可能已经有所发展或是发生改变。

    正在用 React 重构自己的网站,项目用依赖一个外部 js 文件,想在 React 项目中引用进来,并使用其对象,如何处理? 我使用 react-helmet 已经能够引入此外部 js,但是如何使用其中的对象呢?

    下面是我的代码:

    const AppleMusicWaitingState = () => {
    	// 报错 'MusicKit' is not defined
    	document.addEventListener('DOMContentLoaded', function () {
    		MusicKit.configure({
    			developerToken: 'xxxx',
    			app: {
    				name: 'xxxx',
    				icon: "xxxx",
    				build: '2020.12.25'
    			}
    		});
    		e = MusicKit.getInstance();
    	});
    	return <>
    		{/* 引入 apple music */}
    		<Helmet>
    			<title>Apple Music</title>
    			<meta name="apple-music-developer-token" content="xxxx" />
    			<meta name="apple-music-app-name" content="xxxx" />
    			<meta name="apple-music-app-build" content="2020.12.25" />
    			<script src="https://js-cdn.music.apple.com/musickit/v1/musickit.js"></script>
    		</Helmet>
    	</>;
    }
    
    
    3 条回复    2022-09-08 18:06:13 +08:00
    dtdths1
        1
    dtdths1  
       2022-09-08 17:14:26 +08:00   ❤️ 1
    放 useEffect 里,给 script 加监听
    9ki
        2
    9ki  
       2022-09-08 17:37:04 +08:00   ❤️ 2
    blue7wings
        3
    blue7wings  
    OP
       2022-09-08 18:06:13 +08:00
    @9ki 感谢感谢,这个 hook 非常好用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3035 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 14:53 · PVG 22:53 · LAX 07:53 · JFK 10:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.