英文:
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:
<script defer src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous" ></script>
Thanks in Advance
const socket = io("http://localhost:3000/");
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论