ReactJS “io is not defined” 使用 SOCKET IO 的 CDN 链接

huangapple go评论76阅读模式
英文:

ReactJS " io is not defined" using CDN link of SOCKET IO

问题

我不想在我的项目中使用Npm包,所以我尝试使用CDN链接在客户端使用SOCKET IO。

请注意,相同的CDN链接在普通的html/css js中正常工作,但在React项目中不起作用。

我将CDN链接放在React项目的Public文件夹中

这是链接:

<script defer src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous" ></script>


谢谢提前帮助


const socket = io("http://localhost:3000/");


我将这个常量放在类组件之前
英文:

I do not want to use Npm package for my project So i try to use CDN link to use SOCKET IO in client side .

Please Note that same CDN link is working fine in normal html/css js but not in react project.

I put CDN link index.html inside Pubic folder of React project

here it is:

&lt;script defer src=&quot;https://cdn.socket.io/3.1.3/socket.io.min.js&quot;  integrity=&quot;sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh&quot; crossorigin=&quot;anonymous&quot; &gt;&lt;/script&gt;

Thanks in Advance

const socket = io(&quot;http://localhost:3000/&quot;);

I put this constant before class component

答案1

得分: 1

你可以创建一个使用React Hook的功能,该功能使用React useEffect,仅使用JavaScript查询选择head组件并创建一个脚本元素,以手动设置src

或者你可以使用类似React Helmet的库,它允许你在React中轻松处理script的注入,而无需安装该模块。

编辑*

如果你将script放在/public/index.html内,并想要在React中访问io方法的最简单方式是:

const socket = window.io();

英文:

You could create a React Hook which uses a React useEffect that just uses Javascript to query select the head component and create a script element to manually set the src.

Or you could use a library like React Helmet which lets you handle script injection easily within React without needing to install the module.

EDIT*

The absolute bare-bones way to access the io methods in React if you are using placing the script inside /public/index.html is:

const socket = window.io();

huangapple
  • 本文由 发表于 2023年2月10日 04:18:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定