简体   繁体   English

如何在react js中加载脚本? 脚本不起作用

[英]How to load script in react js? script doesn't work

I wanna use video chat from https://websitebeaver.com/insanely-simple-webrtc-video-chat-using-firebase-with-codepen-demo in react.我想在反应中使用来自https://websitebeaver.com/insanely-simple-webrtc-video-chat-using-firebase-with-codepen-demo 的视频聊天。 script worked well when I tried on css+js+html (no react syntax) but script doesn't work after I converted to react当我尝试使用 css+js+html(没有反应语法)时脚本运行良好,但在我转换为反应后脚本不起作用

script.js file located \\chatting\\public\\js\\script.js script.js 文件位于 \\chatting\\public\\js\\script.js

and Video.js file located \\chatting\\src\\components\\Messages\\Video.js和 Video.js 文件位于 \\chatting\\src\\components\\Messages\\Video.js

Video.js (I made this when I click the button, modal opened. and then video call should work) Video.js(当我点击按钮时我做了这个,模式打开。然后视频通话应该可以工作)

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';

class Video extends React.Component {
  componentDidMount() {
    const script = document.createElement('script');

    script.src = '../../../public/js/script.js';
    script.async = true;

    document.body.appendChild(script);
  }

  render() {
    return (
      <Modal trigger={<Icon name="video camera" color="grey" />}>
        <Modal.Header>VideoCall</Modal.Header>
        <Modal.Content image>
          <div className="videoChat">
            <link rel="stylesheet" type="text/css" href="css/style.css" />
            <video
              id="yourVideo"
              autoPlay
              muted
              playsInline
              className="videoChat"
            />
            <video
              id="friendsVideo"
              autoPlay
              playsInline
              className="videoChat"
            />
            <br />
            <button
              onclick="showFriendsFace()"
              type="button"
              className="btn btn-primary btn-lg"
            >
              <span
                className="glyphicon glyphicon-facetime-video"
                aria-hidden="true"
              />{' '}
              Call
            </button>
          </div>
        </Modal.Content>
      </Modal>
    );
  }
}

export default Video;

script.js脚本.js

var firebaseConfig = {
  apiKey: 'I wrote this',
  authDomain: 'I wrote this',
  databaseURL: 'I wrote this',
  projectId: 'I wrote this',
  storageBucket: 'I wrote this',
  messagingSenderId: 'I wrote this',
  appId: 'I wrote this',
  measurementId: 'I wrote this'
};

firebase.initializeApp(firebaseConfig);

var database = firebase.database().ref();
var yourVideo = document.getElementById('yourVideo');
var friendsVideo = document.getElementById('friendsVideo');
var yourId = Math.floor(Math.random() * 1000000000);

var servers = {
  iceServers: [
    { urls: 'stun:stun.services.mozilla.com' },
    { urls: 'stun:stun.l.google.com:19302' },
    {
      urls: 'turn:numb.viagenie.ca',
      credential: 'I wrote this',
      username: 'I wrote this'
    }
  ]
};
var pc = new RTCPeerConnection(servers);
pc.onicecandidate = event =>
  event.candidate
    ? sendMessage(yourId, JSON.stringify({ ice: event.candidate }))
    : console.log('Sent All Ice');
pc.onaddstream = event => (friendsVideo.srcObject = event.stream);

function sendMessage(senderId, data) {
  var msg = database.push({ sender: senderId, message: data });
  msg.remove();
}

function readMessage(data) {
  var msg = JSON.parse(data.val().message);
  var sender = data.val().sender;
  if (sender != yourId) {
    if (msg.ice != undefined) pc.addIceCandidate(new RTCIceCandidate(msg.ice));
    else if (msg.sdp.type == 'offer')
      pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
        .then(() => pc.createAnswer())
        .then(answer => pc.setLocalDescription(answer))
        .then(() =>
          sendMessage(yourId, JSON.stringify({ sdp: pc.localDescription }))
        );
    else if (msg.sdp.type == 'answer')
      pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));
  }
}

database.on('child_added', readMessage);

function showMyFace() {
  navigator.mediaDevices
    .getUserMedia({ audio: true, video: true })
    .then(stream => (yourVideo.srcObject = stream))
    .then(stream => pc.addStream(stream));
}

function showFriendsFace() {
  pc.createOffer()
    .then(offer => pc.setLocalDescription(offer))
    .then(() =>
      sendMessage(yourId, JSON.stringify({ sdp: pc.localDescription }))
    );
}

and index.html和 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="js/script.js"></script>

    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="js/script.js"></script>
  </body>
</html>

componentDidMount() lifecycle method is usually is used for fetching data from an API not for importing js file. componentDidMount() 生命周期方法通常用于从 API 中获取数据,而不是用于导入 js 文件。 Simply just import your script.js in Video.js.只需在 Video.js 中导入您的 script.js。 You should also export the functions you need in script.js and then you can call your functions in your class by adding the name you specified at the first.您还应该在 script.js 中导出您需要的函数,然后您可以通过添加您在第一次指定的名称来调用您的类中的函数。 in code below I only export showFriendsFace() from script.js and called it in Video.js constructor:在下面的代码中,我只从 script.js 导出 showFriendsFace() 并在 Video.js 构造函数中调用它:

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';
import Script from './script'


class Video extends React.Component {
  constructor(){
      super();

      Script.showFriendsFace();
  }

  render() {
    return (
      //your return code
    );
  }
}

export default Video;

and script.js should look like this:和 script.js 应该是这样的:

//your script codes

function showFriendsFace() {
  console.log("Hello World!");
}

export default {showFriendsFace};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM