如何将 JS 代码放入 React 组件中

我有一个 React 组件和我想放入其中的 JS 代码。我试过了,但完全搞砸了。有谁知道该怎么做?


我的组件.js


 import React from "react";

    import Navbar from "./Navbar";


    const Chat = props => (

      <div>

              //Place for my Js code

      </div>

    );


    export default Chat;

javascript代码


<script src="/socket.io/socket.io.js"></script>

      <script>

        var socket = io();


        socket.on('message', function(msg){

          console.log(msg);

          document.getElementById("message").innerHTML = msg;

        });

      </script>


慕森卡
浏览 301回答 2
2回答

慕村9548890

你应该从 npm 导入 socket.io 而不是在 React 中使用 script 标签。并添加代码import io from "socket.io";const Chat = props => {&nbsp; React.useEffect(() => {&nbsp; &nbsp; let socket = io();&nbsp; &nbsp; socket.on('message', function(msg) {&nbsp; &nbsp; &nbsp; console.log(msg);&nbsp; &nbsp; &nbsp; document.getElementById('message').innerHTML = msg;&nbsp; &nbsp; });&nbsp; }, []);&nbsp; return <div></div>;};

四季花海

您可以将代码包装在useEffect钩子中。一旦组件安装,它将触发。您必须sockito.io从npm. 运行 >npm i socket.io-client也添加了一些改进。import React, { useEffect, useRef } from "react";import io from "socket.io-client";const Chat = props => {&nbsp; &nbsp; const socket = useRef(null);&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; connectToSocket();&nbsp; &nbsp; &nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (socket.current) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; socket.current.disconnect()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, []);&nbsp; &nbsp; function connectToSocket() {&nbsp; &nbsp; &nbsp; &nbsp; console.log("Conneting to socket");&nbsp; &nbsp; &nbsp; &nbsp; socket.current = io('http://localhost:5000');&nbsp; &nbsp; &nbsp; &nbsp; socket.current.on('connect', () => console.log("Connected"));&nbsp; &nbsp; &nbsp; &nbsp; socket.current.on('disconnect', () => connectToSocket());&nbsp; &nbsp; &nbsp; &nbsp; socket.current.on('message', function (msg) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(msg);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("message").innerHTML = msg;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; return (<div>&nbsp; &nbsp; &nbsp; &nbsp; Some data&nbsp; &nbsp; &nbsp; &nbsp; <div id="message"></div>&nbsp; &nbsp; </div>)}export default Chat;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript